﻿module Sustainalytics.Screening {

    import Common = Sustainalytics.Common;

    export interface IScreeningToolControllerScope extends ng.IScope {
        tool: any;
        currentSelection: string;
        selectCriteria: any;
        getTypeSevenSelectedItemsNames: () => void;
        getTypeSevenItemName: (item: string) => string;
        selectedCriteria: ISelectedCriteria;
        currentFilter: IScreeningToolFilter;
        applyCurrentFilter: (filter: IScreeningToolFilter) => void;
        currentCriteriaTypeOne: ICriteriaTypeOne;
        currentCriteriaTypeThree: ICriteriaTypeThree;
        currentCriteriaTypeSix: ICriteriaTypeSix;
        currentCriteriaTypeFive: ICriteriaTypeFive;
        currentCriteriaTypeSeven: ICriteriaTypeSeven;
        tabs: ICriteriaTabs[];

        gcSelectedItems: any;

        criteriaTypeOneChart: any;
        criteriaTypeSixChart: any;
        addSelectedCriteria: any;
        updateSelectedCriteria: any;
        selectedCriteriaScore: any;
        tabChanged: any;
        userTabChanged: any;
        portfolios: any;
        currentPortfolio: any;
        sortableOptions: any;
        deleteCriteria: any;
        updateCriteria: any;
        selectedFilterCriteria: ISelectedCriteria;
        baseCriteriaList: IBaseCriteria[];
        loadBaseCriteriaList: any;
        loadBaseCriteria: any;
        baseCriteriaSelected: any;
        searchText: string;
        deleteSelectedItems: (item: string) => void;
        deleteCriteriaTypeSevenSelectedItems: (item: string) => void;
        addItemToSelectedItems: (item: string) => void;
        addCriteriaTypeSevenItemToSelectedItems: (item: string) => void;
        searchInCollection: () => void;
        loadCriteriaTypeThreeCollectionItems: (loadMore: boolean) => void;
        loadCriteriaTypeSevenCollectionItems: (loadMore: boolean) => void;
        initSignalR: any;
        criteriaHub: ProcessHubProxy;
        open: (size) => void;
        lastUsedFilters: any;
        asyncLoadFiltersOperation: Sustainalytics.Common.AsyncHttpOperation<any>;
        ensureLatestFilters: (any) => void;
        runCurrentCriteria: () => ng.IPromise<{}>;
        runCriteria: (filterId: string) => ng.IPromise<{}>;
        exportCriteria: () => void;
        getResultOutput: (pageIndex?: number, pageSize?: number) => ng.IPromise<{}>;
        deleteAllCriteria: (filterId: string) => ng.IPromise<{}>;
        clearResultOutput: () => ng.IPromise<{}>;
        refreshResultOutputs: () => ng.IPromise<{}>;
        resultOutputPaged: Common.PagedList<IResultOutput>;
        resultOutputFilter: ResultOutputFilter;
        resultOutputOrderBy: string;
        resultOutputOrderByAscending: boolean;
        toggleResultOutputOrder: (orderBy: string) => void;
        computeResultOutputFilterIsValid: () => void;
        predefinedCols: any;
        filterResultOutput: (criteria) => any;
        isCriteriaValid: (criteria) => any;
        isNamedCriteriaValid: (name, companyCriterias) => any;
        getCriteriaClassName: (isValid) => any;
        saveFilter: (saveNew: boolean) => void;

        isSelectionValid: () => boolean;

        screenOnAnyInvolvementChecked: () => void;
        screenOnAnyInvolvementUncheck: () => void;
        typeFourHasAnyInvolvement: (selectedCriteria: ISelectedCriteria) => boolean;

        asyncLoadSavedFilter: Sustainalytics.Common.AsyncHttpOperation<any>;
        loadSavedFilter: (filter: IFilter, requiresConfirmation: boolean) => any;
        loadUniverses: () => void;
        isLatestDropDownOpen: boolean;
        selectPortfolio: any;
        //AddPortfolio
        openSavePortfolio: () => void;
        cancel: () => void;
        //modalInstance: IModalInstance;
        // getPortfolioCompanies: () => string[];
        resultOutputIsValidVisible: boolean;
        openFilterContainer: () => void;
        hideFilterContainer: () => void;
        selectedCriteriaIsrunning: boolean;
        exportScreeningDetails: ExportDetailsDto;
        hasPortfolioPermision: boolean;
        getTemplateCriteriaClass: (isActive: boolean, isEnabled: boolean) => string;

        asyncLoadStandardFilter: Sustainalytics.Common.AsyncHttpOperation<any>;
        loadStandardFilter: (standardFilterType: StandardFilter, requiresConfirmation: boolean) => any;

        accountUniverses: IUniverse[];
        accountUniverseSelected: (universeId: number) => void;
        accountUniverseId: number;
        universeSearchText: any;
    }

    class ScreeningToolController {
        constructor(
            private $scope: IScreeningToolControllerScope,
            $rootScope,
            $q: ng.IQService,
            $modal: Common.IModal,
            notificationFactory: Common.INotificationFactory,
            staticObjects: Common.IStaticObjects,
            screeningToolFactory: IScreeningToolFactory,
            private PortfolioService: Sustainalytics.Portfolio.PortfolioService,
            $timeout) {

            $scope.tool = { template: 'Views/Tools/ScreeningTool/ScreeningTool.html' };
            $scope.currentSelection = "";
            $scope.isLatestDropDownOpen = false;
            $scope.baseCriteriaList = [];
            $scope.currentPortfolio = { id: "", name: "" };
            this.PortfolioService = PortfolioService;
            $scope.hasPortfolioPermision = this.PortfolioService.hasPermision();
            console.log($scope.hasPortfolioPermision);
            $scope.getTemplateCriteriaClass = (isActive, isEnabled) => {
                var className = "";

                if (isActive)
                    className = "active";

                if (!isEnabled && isEnabled != undefined)
                    className = "disabled";

                return className;
            };
            var buildGcSelectedItemsText: () => void;
            $scope.selectPortfolio = (selectedPortfolio) => {
                if ($scope.currentPortfolio != selectedPortfolio) {
                    $scope.currentPortfolio = selectedPortfolio;
                    
                    $rootScope['screeningExportDetails'].SelectedPortfolio = selectedPortfolio;
                    
                    refreshSelectedCriteriaCompaniesCount();
                    $scope.clearResultOutput();
                }
            };

            var refreshSelectedCriteriaCompaniesCount = () => {
                $scope.currentFilter.selectedCriteria.forEach((filterCriteria) => {
                    filterCriteria.companyCount = null;
                    $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filterCriteria.id, filterCriteria.type, $scope.currentPortfolio.id, $scope.accountUniverseId);
                });
            };

            $scope.$on("searchBoxClosed", (e, val) => {
                var inputVal = $('#portfolioSearchInput').val();
                if (inputVal == "" && inputVal != $scope.currentPortfolio.name) {
                    $scope.currentPortfolio = { id: "", name: "" };
                    $rootScope['screeningExportDetails'].SelectedPortfolio = undefined;
                    refreshSelectedCriteriaCompaniesCount();
                }
            });

            $scope.predefinedCols =
            {
                'Company': true,
                'Exchange': true,
                'Ticker': true,
                'Company name': true
            };

            $scope.filterResultOutput = (criteria) => {
                return !$scope.predefinedCols[criteria.name];
            }

            $scope.isCriteriaValid = (criteria) => {
                return criteria.isValid;
            }

            $scope.isNamedCriteriaValid = (name, companyCriterias) => {
                var isValid = true;

                $(companyCriterias).filter(function () { return this.name == name; }).each(function () {
                    var criteria = this;
                    isValid = $scope.isCriteriaValid(criteria);
                });

                return isValid;
            }

            $scope.getCriteriaClassName = (isValid) => {
                if (isValid == null) {
                    return null;
                }
                else {
                    return isValid ? 'screening-criteria-valid' : 'screening-criteria-invalid';
                }
            }

            // init result output filter
            $scope.resultOutputFilter = new ResultOutputFilter();
            $scope.resultOutputFilter.isValidEnabled = true;
            $scope.resultOutputFilter.isNotValidEnabled = true;
            $scope.resultOutputFilter.isValid = null;

            var setIsModified = (isModifed: boolean) => {
                if ($scope.currentFilter) {
                    $scope.currentFilter.isModified = isModifed;
                }
            };

            $scope.getResultOutput = (pageIndex, pageSize) => {
                $rootScope.loading = true;
                var def = $q.defer();

                // get pager
                var pager: Sustainalytics.Pager.PagerController = $scope['pager'];

                // If pager is not defined then abort execution.
                // Current controller is created before Pager controller.
                if (!pager) {
                    $rootScope.loading = false;
                    return;
                }


                if (pageIndex) {
                    pager.pagingOptions.pageIndex = pageIndex;
                }

                if (pageSize) {
                    pager.pagingOptions.pageSize = pageSize;
                }
                if ($scope.resultOutputFilter.filterId != null) {

                    var skip = pager.pagingOptions.pageSize * (pager.pagingOptions.pageIndex - 1);
                    var take = pager.pagingOptions.pageSize;

                    screeningToolFactory.getResultOutput($scope.resultOutputFilter, skip, take, $scope.resultOutputOrderBy, $scope.resultOutputOrderByAscending)
                        .success((result: GetRunResultDto) => {
                            var resultOutputPaged = new Sustainalytics.Common.PagedList<IResultOutput>();

                            resultOutputPaged.items = result.items;
                            resultOutputPaged.pagingOptions = pager.pagingOptions;
                            resultOutputPaged.totalItemsCount = result.count;
                            resultOutputPaged.totalPageCount = Math.ceil(result.count / pager.pagingOptions.pageSize);

                            $scope.resultOutputPaged = resultOutputPaged;
                            pager.totalItemsCount = result.count;

                            def.resolve();
                            $rootScope.loading = false;
                        }).error((data, status, headers, config, statusText) => {
                            $rootScope.loading = false;
                            notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));

                            ga('create', 'UA-4379897-6', {
                                'userId': $rootScope.userInfo.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                            });

                            ga('globalAccess.send', 'exception', { 'exDescription': 'ScreeningTool: ResultOutput -> ' + staticObjects.getErrorMesageByStatusCode(status, data)});

                            def.reject();
                        });
                }
                else {
                    $rootScope.loading = false;
                    def.reject();
                }

                return def.promise;
            };

            $scope.loadBaseCriteriaList = () => {
                $rootScope['screeningExportDetails'] = new ExportDetailsDto();
                screeningToolFactory.listBaseCriteria().then(data => {
                    $scope.baseCriteriaList.length = 0;
                    angular.forEach(data, baseCriteria => {
                        $scope.baseCriteriaList.push(baseCriteria);
                    })
                }, error => {
                        //notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                    });
            }

            $scope.toggleResultOutputOrder = (orderBy) => {
                var currentOrderBy = $scope.resultOutputOrderBy;

                if (orderBy === currentOrderBy) {
                    $scope.resultOutputOrderByAscending = !$scope.resultOutputOrderByAscending;
                }
                else {
                    $scope.resultOutputOrderBy = orderBy;
                    $scope.resultOutputOrderByAscending = true;
                }
            }

            // subscribe to properties which drive how result output retrieval is done
            $scope.$watch('resultOutputOrderBy', function () { $scope.getResultOutput(); });
            $scope.$watch('resultOutputOrderByAscending', function () { $scope.getResultOutput(); });
            $scope.$watch('resultOutputFilter.isValid', function () { $scope.getResultOutput(1); });
            $scope.$watch('resultOutputIsValidVisible', function () { $scope.computeResultOutputFilterIsValid(); });
            $scope.$watch('resultOutputFilter.isValidEnabled', function () { $scope.computeResultOutputFilterIsValid(); });
            $scope.$watch('resultOutputFilter.isNotValidEnabled', function () { $scope.computeResultOutputFilterIsValid(); });

            $scope.computeResultOutputFilterIsValid = () => {
                var filter = $scope.resultOutputFilter;
                var isValid = null;

                if ((filter['isValidEnabled'] && filter['isNotValidEnabled']) || (!filter['isValidEnabled'] && !filter['isNotValidEnabled'])) {
                    isValid = null;
                }
                else {
                    if (filter['isValidEnabled']) {
                        isValid = true;
                    }
                    else {
                        if (filter['isNotValidEnabled']) {
                            isValid = false;
                        }
                    }
                }

                $scope.resultOutputFilter.isValid = isValid;
            };

            $scope.applyCurrentFilter = (filter: IScreeningToolFilter) => {

                // text formatting for criteria type 5 on load 
                filter.selectedCriteria.forEach((item: ISelectedCriteria) => {
                    if (item.type == 5) {
                        item.typeFiveAnswersText = screeningToolFactory.composeAnswerTextCriteriaTypeFive(item.typeFiveScoreAnswers, item.typeFiveScore);
                    }

                    if (item.type == 7) {
                        $scope.selectedCriteria.typeSevenText = $.map(item.typeSevenSelectedItems, (item, index) => {
                            return $scope.getTypeSevenItemName(item);
                        }).join(' or ');

                        item.typeSevenText = $scope.selectedCriteria.typeSevenText;
                    }
                });

                $scope.currentFilter = filter;
                $scope.resultOutputFilter.filterId = $scope.currentFilter.filterId;
                //$scope.getResultOutput(1);
                $scope.clearResultOutput();

                if (filter.selectedCriteria.length > 0) {
                    for (var i = 0; i < filter.selectedCriteria.length; i++) {
                        $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filter.selectedCriteria[i].id, filter.selectedCriteria[i].type, $scope.currentPortfolio.id, 0);
                    }
                }
            }

            $scope.initSignalR = () => {
                //Set the hubs URL for the connection

                $.connection.hub.url = "screeningtoolserv/signalr";
                if ($rootScope.authData && $rootScope.authData.access_token) {
                    $.connection.hub.qs = { "access_token": $rootScope.authData.access_token };
                }
                // Declare a proxy to reference the hub.
                $scope.criteriaHub = (<any>$.connection).selectedCriteriaManagerHub;

                $scope.criteriaHub.client.setCompaniesCount = (criteriaId, count) => {
                    var emitOptions = { criteriaId: criteriaId, count: count };
                    $rootScope.$emit("setCompaniesCount", emitOptions);
                };
                var updateCount = (criteriaId, count) => {
                    for (var i = 0; i < $scope.currentFilter.selectedCriteria.length; i++) {
                        if ($scope.currentFilter.selectedCriteria[i].id == criteriaId) {
                            $scope.currentFilter.selectedCriteria[i].companyCount = count;
                            break;
                        }
                    }
                }

                $rootScope.$on("setCompaniesCount", (e, emitOptions) => {
                    $scope.$evalAsync(() => {
                        updateCount(emitOptions.criteriaId, emitOptions.count);
                    });
                });

                $.connection.hub.start().done(() => {
                    var promise = screeningToolFactory.getCurrentFilter();
                    promise
                        .success($scope.applyCurrentFilter)
                        .error((data, status, headers, config, statusText) => {
                            notificationFactory.error("Error initializing SignalR", staticObjects.getErrorMesageByStatusCode(status, data));
                        });
                });
            }

            // subscribe to pager events
            $scope.$on('pagerChanged', function (event, pager) {
                // get results
                if ($scope.currentFilter) {
                    $scope.getResultOutput();
                }
            });

            $scope.loadUniverses = () => {
                $scope.accountUniverseId = 0;

                screeningToolFactory.loadUniverses().success((result: IUniverse[]) => {
                    this.$scope.accountUniverses = result;
                }).error((error) => {
                    ga('create', 'UA-4379897-6', {
                        'userId': $rootScope.userInfo.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                    });

                    ga('globalAccess.send', 'exception', { 'exDescription': 'Screening Tool: There was an error retrieving your universes.' });

                    notificationFactory.error("There was an error retrieving your universes.", "");
                });
            };

            $scope.loadBaseCriteriaList();
            $scope.initSignalR();
            $scope.loadUniverses();
            
            $scope.baseCriteriaSelected = (baseCriteria: IBaseCriteria) => {
                var bCriteria =  activateTabForBaseCriteriaName(baseCriteria.name);

                $scope.selectCriteria(bCriteria);
                $scope.selectedCriteria.loading = true;

                $scope.searchText = "";
            }

            $scope.accountUniverseSelected = (universeId: number) => {
                $scope.accountUniverseId = universeId;
                refreshSelectedCriteriaCompaniesCount()
            };


            var activateTabForBaseCriteriaName = (name: string): IBaseCriteria => {
                for (var i = 0; i < $scope.tabs.length; i++) {
                    var parentTab = $scope.tabs[i];
                    for (var j = 0; j < parentTab.childItems.length; j++) {
                        var childTab = parentTab.childItems[j];
                        for (var w = 0; w < childTab.baseCriteria.length; w++) {
                            var baseCriteria = childTab.baseCriteria[w];

                            if (baseCriteria.name == name) {
                                parentTab.active = true;
                                childTab.active = true;

                                return baseCriteria;
                            };
                        }
                    }
                }
            };

            var activateBaseCriteria = (name: string) => {
                for (var i = 0; i < $scope.tabs.length; i++) {
                    var parentTab = $scope.tabs[i];
                    for (var j = 0; j < parentTab.childItems.length; j++) {
                        var childTab = parentTab.childItems[j];
                        for (var w = 0; w < childTab.baseCriteria.length; w++) {
                            var baseCriteria = childTab.baseCriteria[w];

                            if (baseCriteria.name == name) {
                                baseCriteria.isActive = true;
                            } else {
                                baseCriteria.isActive = false;
                            };
                        }
                    }
                }
            };

           
            $scope.selectedCriteria = {
                typeOneMaxValue: null,
                typeOneMinValue: null,
                typeThreeCollectionName: "",
                typeThreeSelectedItems: [],
                typeSevenCollectionName: "",
                typeSevenSelectedItems: [],
                typeTwoBaseEventIndicatorId: null,
                typeTwoScore: 0,
                typeFiveScore: -1,
                typeFiveTemplateIndicatorNumber: null,
                typeFiveScoreAnswers: [],
                typeFiveAnswersText: "",
                id: null,
                type: null,
                name: null,
                loading: false,
                isUpdating: false,
                companyCount: undefined,
                typeSixMinValue: 0,
                typeSixMaxValue: 0,
                typeEightScore: 0,
                typeEightTemplateIndicatorNumber: null,
                typeSevenText: "",
                typeFourCategories: [],
                typeFourSymbol: "",
                typeFourScreenOnAnyInvolvement: false,
                typeFourSelectedCriteria: null
            };

            // controls  the "add criteria" button state (enbled or disabled) 
            $scope.isSelectionValid = () => {

                if ($scope.selectedCriteria.type == 5) {
                    if ($scope.currentCriteriaTypeFive != null && $scope.currentCriteriaTypeFive.score > -1)
                        return true;
                    else
                        return false;
                }
                if ($scope.selectedCriteria.type == 2) {
                    if ($scope.selectedCriteria != null && $scope.selectedCriteria.typeTwoScore > 0)
                        return true;
                    else
                        return false;
                }
                if ($scope.selectedCriteria.type == 3) {
                    if ($scope.selectedCriteria != null && $scope.selectedCriteria.typeThreeSelectedItems.length > 0)
                        return true;
                    else
                        return false;
                }
                if ($scope.selectedCriteria.type == 1) {

                    if ($scope.criteriaTypeOneChart)
                        return !$scope.criteriaTypeOneChart.invalidInput();
                }

                if ($scope.selectedCriteria.type == 6) {

                    if ($scope.criteriaTypeSixChart)
                        return !$scope.criteriaTypeSixChart.invalidInput();
                }

                if ($scope.selectedCriteria.type == 7) {
                    if ($scope.selectedCriteria != null && $scope.selectedCriteria.typeSevenSelectedItems.length > 0)
                        return true;
                    else
                        return false;
                }
                if ($scope.selectedCriteria.type == 8) {

                    if ($scope.selectedCriteria != null && $scope.selectedCriteria.typeEightScore > 0)
                        return true;
                    else
                        return false;
                }
                if ($scope.selectedCriteria.type == 4) {

                    var returnValue = false;

                    $scope.selectedCriteria.typeFourCategories.forEach((category) => {
                        if (category.revenueRange.length > 0) {
                            if (category.isSignificantOwnership || (category.selectedValue != undefined && category.selectedValue != 0))
                                returnValue = true;
                        }
                        else {
                        if (category.isInvolved || category.isSignificantOwnership)
                            returnValue = true;
                        }
                    });

                    return returnValue;
                }

                return true;
            }

            $scope.screenOnAnyInvolvementChecked = () => {
                if ($scope.selectedCriteria.typeFourScreenOnAnyInvolvement) {
                    $scope.selectedCriteria.typeFourCategories.forEach((category) => {
                        if (category.significantOwnershipYesNo)
                            category.isSignificantOwnership = true;
                        if (category.revenueRange.length == 0)
                            category.isInvolved = true;
                        if (category.revenueRange.length > 0)
                            category.selectedValue = category.maxValue;
                    });
                }

                $scope.selectedCriteria.typeFourScreenOnAnyInvolvement = true;
            }

            $scope.screenOnAnyInvolvementUncheck = () => {
                $scope.selectedCriteria.typeFourScreenOnAnyInvolvement = false;
            }


            $scope.typeFourHasAnyInvolvement = (selectedCriteria: ISelectedCriteria): boolean => {
                var returnValue = false;
                selectedCriteria.typeFourCategories.forEach((category) => {
                    if (category.revenueRange.length == 0) {
                        if (category.isInvolved || category.isSignificantOwnership)
                            returnValue = true;
                    }

                    if (category.revenueRange.length > 0) {
                        if ((category.selectedValue != undefined && category.selectedValue > 0) || category.isSignificantOwnership)
                            returnValue = true;
                    }
                });

                return returnValue;
            };

            $scope.tabChanged = (data: ICriteriaTabs, lowerLevel: boolean) => {
                if (!$scope.selectedCriteria.loading)
                    $scope.currentSelection = "";

                if (data.name == 'Global Compact' && !$scope.selectedCriteria.loading) {
                    $scope.selectCriteria(data.childItems[0].baseCriteria[0]);
                }

                if (lowerLevel)
                    $scope.selectedCriteria.loading = false;
            };

            $scope.userTabChanged = (data: ICriteriaTabs) => {
                $scope.currentSelection = "";
                if (data.name == 'Global Compact') {
                    $scope.selectCriteria(data.childItems[0].baseCriteria[0]);
                }
                $scope.selectedCriteria.loading = false;
            };

            $scope.sortableOptions = {
                stop: (event, ui) => {
                    updateSelectedCriteriaOrderNumber();
                }
            };

            $scope.updateCriteria = (selectedCriteria: ISelectedCriteria) => {
                var baseCriteria = activateTabForBaseCriteriaName(selectedCriteria.name);
                activateBaseCriteria(selectedCriteria.name);
                switch (baseCriteria.type) {
                    case 1:
                        $scope.currentSelection = "criteriatypeone.tpl.htm";
                        screeningToolFactory.loadCriteriaTypeOne(baseCriteria.id).success((criteriaTypeOne: ICriteriaTypeOne) => {
                            $scope.currentCriteriaTypeOne = criteriaTypeOne;
                            $scope.criteriaTypeOneChart = {};

                            var yAxis = [];
                            $scope.criteriaTypeOneChart.xAxis = [];
                            $scope.currentCriteriaTypeOne.criteriaData.forEach(function (item) {
                                $scope.criteriaTypeOneChart.xAxis.push(item.xAxisValue);
                                yAxis.push(item.yAxisValue);
                            });


                            var data = {
                                labels: $scope.criteriaTypeOneChart.xAxis,
                                datasets: [
                                    {
                                        label: "Companies",
                                        fillColor: "rgba(220,220,220,0.5)",
                                        strokeColor: "rgba(220,220,220,0.8)",
                                        highlightFill: "rgba(220,220,220,0.75)",
                                        highlightStroke: "rgba(220,220,220,1)",
                                        data: yAxis
                                    }
                                ]
                            };

                            var options = {
                                scaleBeginAtZero: true,
                                showTooltips: false,
                                scaleShowGridLines: false,
                                scaleGridLineColor: "rgba(0,0,0,0)",
                                barValueSpacing: 12
                            };

                            $scope.criteriaTypeOneChart.minValue = selectedCriteria.typeOneMinValue;
                            $scope.criteriaTypeOneChart.maxValue = selectedCriteria.typeOneMaxValue;
                            $scope.criteriaTypeOneChart.data = data;
                            $scope.criteriaTypeOneChart.options = options;
                            $scope.criteriaTypeOneChart.invalidInput = () => {
                                if (!$scope.criteriaTypeOneChart.minValue) return true;
                                if (!$scope.criteriaTypeOneChart.maxValue) return true;

                                var min = parseInt($scope.criteriaTypeOneChart.minValue);
                                var max = parseInt($scope.criteriaTypeOneChart.maxValue);

                                if (isNaN(min) || isNaN(max))
                                    return true;

                                var rangeMin = Math.min.apply(Math, $scope.criteriaTypeOneChart.xAxis);
                                var rangeMax = Math.max.apply(Math, $scope.criteriaTypeOneChart.xAxis);

                                if (min > max)
                                    return true;

                                if (rangeMin > min)
                                    return true;

                                if (rangeMax < max)
                                    return true;

                                return false;
                            };
                        }).error((data, status, headers, config, statusText) => {
                                notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                            });
                        break;
                    case 2:
                        $scope.currentSelection = "criteriaType2.tpl.htm";
                        $scope.selectedCriteria.typeTwoScore = convertSliderValue(selectedCriteria.typeTwoScore);
                        break;
                    case 3:
                        $scope.currentSelection = "criteriaType3.tpl.htm";
                        screeningToolFactory.loadCriteriaTypeThree(baseCriteria.id, 0, 20).success((criteriaTypeThree: ICriteriaTypeThree) => {
                            $scope.currentCriteriaTypeThree = criteriaTypeThree;
                            $scope.currentCriteriaTypeThree.filter = "";
                            $scope.selectedCriteria.typeThreeSelectedItems = selectedCriteria.typeThreeSelectedItems;
                            $scope.selectedCriteria.typeThreeCollectionName = criteriaTypeThree.collectionName;

                        }).error((data, status, headers, config, statusText) => {
                                notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                            });
                        break;
                    case 4:
                        $scope.currentSelection = "criteriaType4.tpl.htm";
                        $scope.selectedCriteria.typeFourSelectedCriteria = selectedCriteria.typeFourSelectedCriteria;
                        var selectedValues = [-1,50,25,10,5,0];

                        screeningToolFactory.loadCriteriaTypeFourCategories(baseCriteria.symbol).success((criteriaTypeFourCategories: ICriteriaTypeFourCategories[]) => {
                            $scope.selectedCriteria.name = baseCriteria.name;
                            $scope.selectedCriteria.type = baseCriteria.type;
                            $scope.selectedCriteria.typeFourCategories = criteriaTypeFourCategories;
                            $scope.selectedCriteria.typeFourSymbol = baseCriteria.symbol;
                            $scope.selectedCriteria.typeFourScreenOnAnyInvolvement = false;

                            screeningToolFactory.loadCriteriaTypeFour(selectedCriteria.typeFourSelectedCriteria.piFilterCriteriaId).success((criteria: any) => {
                                $scope.selectedCriteria.typeFourCategories.forEach((category) => {
                                    criteria.forEach((criteria) => {
                                        if (criteria.piCategory.categorySymbol == category.categorySymbol) {
                                            if (criteria.piCategory.isInvolvement)
                                                category.isInvolved = true;
                                            if (criteria.piCategory.isSignificantOwnership)
                                                category.isSignificantOwnership = true;
                                            if (!criteria.piCategory.isSignificantOwnership && !criteria.piCategory.isInvolvement)
                                                category.selectedValue = selectedValues.indexOf(criteria.piCategory.start);
                                        }
                                    });
                                });
                            }).error(data => {
                                    notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(data));
                                });

                        }).error(data => {
                                notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(data));
                            });

                        
                        break;
                    case 5://criteriafive

                        $scope.currentSelection = "criteriaType5.tpl.htm";
                        screeningToolFactory.loadCriteriaTypeFive(selectedCriteria.id).success((criteriaTypeFive: ICriteriaTypeFive) => {
                            $scope.currentCriteriaTypeFive = criteriaTypeFive;
                        }).error((data, status, headers, config, statusText) => {
                                notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                            });
                        break;
                    case 6:
                        $scope.currentSelection = "criteriatypesix.tpl.htm";
                        screeningToolFactory.loadCriteriaTypeSix(baseCriteria.id).success((criteriaTypeSix: ICriteriaTypeSix) => {
                            $scope.currentCriteriaTypeSix = criteriaTypeSix;

                            if (selectedCriteria.typeSixMaxValue > criteriaTypeSix.maxValue || selectedCriteria.typeSixMaxValue == 0)
                                selectedCriteria.typeSixMaxValue = criteriaTypeSix.maxValue;

                            if (selectedCriteria.typeSixMinValue < criteriaTypeSix.minValue)
                                selectedCriteria.typeSixMinValue = criteriaTypeSix.minValue

                            $scope.criteriaTypeSixChart = {};

                            var yAxis = [];
                            $scope.criteriaTypeSixChart.xAxis = [];
                            $scope.currentCriteriaTypeSix.criteriaData.forEach(function (item) {
                                $scope.criteriaTypeSixChart.xAxis.push(item.xAxisValue);
                                yAxis.push(item.yAxisValue);
                            });


                            var data = {
                                labels: $scope.criteriaTypeSixChart.xAxis,
                                datasets: [
                                    {
                                        label: "Companies",
                                        fillColor: "rgba(220,220,220,0.5)",
                                        strokeColor: "rgba(220,220,220,0.8)",
                                        highlightFill: "rgba(220,220,220,0.75)",
                                        highlightStroke: "rgba(220,220,220,1)",
                                        data: yAxis
                                    }
                                ]
                            };

                            var options = {
                                scaleBeginAtZero: true,
                                showTooltips: false,
                                scaleShowGridLines: false,
                                scaleGridLineColor: "rgba(0,0,0,0)",
                                barValueSpacing: 7
                            };

                            $scope.criteriaTypeSixChart.minValue = selectedCriteria.typeSixMinValue;
                            $scope.criteriaTypeSixChart.maxValue = selectedCriteria.typeSixMaxValue;
                            $scope.criteriaTypeSixChart.data = data;
                            $scope.criteriaTypeSixChart.options = options;
                            $scope.criteriaTypeSixChart.invalidInput = () => {
                                if (!$scope.criteriaTypeSixChart.minValue) return true;
                                if (!$scope.criteriaTypeSixChart.maxValue) return true;

                                var min = parseInt($scope.criteriaTypeSixChart.minValue);
                                var max = parseInt($scope.criteriaTypeSixChart.maxValue);

                                if (isNaN(min) || isNaN(max))
                                    return true;

                                var rangeMin = Math.min.apply(Math, $scope.criteriaTypeSixChart.xAxis);
                                var rangeMax = Math.max.apply(Math, $scope.criteriaTypeSixChart.xAxis);

                                if (min > max)
                                    return true;

                                if (rangeMin > min)
                                    return true;

                                if (rangeMax < max)
                                    return true;

                                return false;
                            };
                        }).error((data, status, headers, config, statusText) => {
                                notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                            });
                        break;
                    case 7:
                        $scope.currentSelection = "criteriaType7.tpl.htm";
                        screeningToolFactory.loadCriteriaTypeSeven(baseCriteria.id, 0, 20).success((criteriaTypeSeven: ICriteriaTypeSeven) => {
                            $scope.currentCriteriaTypeSeven = criteriaTypeSeven;
                            $scope.currentCriteriaTypeSeven.filter = "";
                            //$timeout(() => {
                            //    $scope.$apply(() => {
                            $scope.selectedCriteria.typeSevenSelectedItems = selectedCriteria.typeSevenSelectedItems;
                            //    });
                            //});
                            buildGcSelectedItemsText();
                        }).error((data, status, headers, config, statusText) => {
                                notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                            });
                        break;
                    case 8:
                        $scope.currentSelection = "criteriaType8.tpl.htm";
                        $scope.selectedCriteria.typeEightScore = convertSliderValue(selectedCriteria.typeEightScore);
                        break;
                    default:
                        $scope.currentSelection = "";
                        break;
                }

                $scope.selectedCriteria.loading = true;
                $scope.selectedCriteria.isUpdating = true;
                $scope.selectedFilterCriteria = selectedCriteria;
                $scope.selectedCriteria.id = baseCriteria.id;
                $scope.selectedCriteria.name = baseCriteria.name;
                $scope.selectedCriteria.type = baseCriteria.type;
            };

            var updateSelectedCriteriaOrderNumber = () => {
                var criteriaIds: Array<string> = [];
                $scope.currentFilter.selectedCriteria.forEach((item: ISelectedCriteria) => {
                    criteriaIds.push(item.id);
                });
                screeningToolFactory.updateSelectedCriteriaOrderNumber($scope.currentFilter.filterId, criteriaIds).error((data, status, headers, config, statusText) => {
                    notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                });;
            };

            $scope.deleteCriteria = (criteria: ISelectedCriteria) => {
                setIsModified(true);
                screeningToolFactory.deleteCriteria(criteria.id).success(() => {
                    var index = $scope.currentFilter.selectedCriteria.indexOf(criteria);
                    $scope.currentFilter.selectedCriteria.splice(index, 1);
                    updateSelectedCriteriaOrderNumber();
                    //$scope.refreshResultOutputs();
                    $scope.clearResultOutput();
                }).error((data, status, headers, config, statusText) => {
                        notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                    });
            };

            $scope.selectCriteria = (baseCriteria: IBaseCriteria) => {
                $scope.selectedCriteria.loading = false;
                $scope.selectedCriteria.isUpdating = false;
                $scope.selectedCriteria.id = baseCriteria.id;
                $scope.selectedCriteria.name = baseCriteria.name;
                $scope.selectedCriteria.type = baseCriteria.type;
                activateBaseCriteria(baseCriteria.name);
                switch (baseCriteria.type) {
                    case 1:
                        $scope.currentSelection = "criteriatypeone.tpl.htm";
                        screeningToolFactory.loadCriteriaTypeOne(baseCriteria.id).success((criteriaTypeOne: ICriteriaTypeOne) => {
                            $scope.currentCriteriaTypeOne = criteriaTypeOne;
                            $scope.criteriaTypeOneChart = {};

                            var yAxis = [];
                            $scope.criteriaTypeOneChart.xAxis = [];
                            $scope.currentCriteriaTypeOne.criteriaData.forEach(function (item) {
                                $scope.criteriaTypeOneChart.xAxis.push(item.xAxisValue);
                                yAxis.push(item.yAxisValue);
                            });


                            var data = {
                                labels: $scope.criteriaTypeOneChart.xAxis,
                                datasets: [
                                    {
                                        label: "Companies",
                                        fillColor: "rgba(220,220,220,0.5)",
                                        strokeColor: "rgba(220,220,220,0.8)",
                                        highlightFill: "rgba(220,220,220,0.75)",
                                        highlightStroke: "rgba(220,220,220,1)",
                                        data: yAxis
                                    }
                                ]
                            };

                            var options = {
                                scaleBeginAtZero: true,
                                showTooltips: false,
                                scaleShowGridLines: false,
                                scaleGridLineColor: "rgba(0,0,0,0)",
                                barValueSpacing: 12
                            };

                            $scope.criteriaTypeOneChart.minValue = $scope.criteriaTypeOneChart.xAxis[0];
                            $scope.criteriaTypeOneChart.maxValue = $scope.criteriaTypeOneChart.xAxis[$scope.criteriaTypeOneChart.xAxis.length - 1];
                            $scope.criteriaTypeOneChart.data = data;
                            $scope.criteriaTypeOneChart.options = options;
                            $scope.criteriaTypeOneChart.invalidInput = () => {
                                if (!$scope.criteriaTypeOneChart.minValue) return true;
                                if (!$scope.criteriaTypeOneChart.maxValue) return true;

                                var min = parseInt($scope.criteriaTypeOneChart.minValue);
                                var max = parseInt($scope.criteriaTypeOneChart.maxValue);

                                if (isNaN(min) || isNaN(max))
                                    return true;

                                var rangeMin = Math.min.apply(Math, $scope.criteriaTypeOneChart.xAxis);
                                var rangeMax = Math.max.apply(Math, $scope.criteriaTypeOneChart.xAxis);

                                if (min > max)
                                    return true;

                                if (rangeMin > min)
                                    return true;

                                if (rangeMax < max)
                                    return true;

                                return false;
                            };
                        }).error((data, status, headers, config, statusText) => {
                                notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                            });
                        break;
                    case 2:
                        $scope.currentSelection = "criteriaType2.tpl.htm";
                        $scope.selectedCriteria.typeTwoScore = 0;
                        break;
                    case 3:
                        $scope.currentSelection = "criteriaType3.tpl.htm";
                        screeningToolFactory.loadCriteriaTypeThree(baseCriteria.id, 0, 20).success((criteriaTypeThree: ICriteriaTypeThree) => {
                            $scope.currentCriteriaTypeThree = criteriaTypeThree;
                            $scope.currentCriteriaTypeThree.filter = "";
                            $scope.selectedCriteria.typeThreeSelectedItems = criteriaTypeThree.selectedItems != null ? criteriaTypeThree.selectedItems : [];
                            $scope.selectedCriteria.typeThreeCollectionName = criteriaTypeThree.collectionName;

                        }).error((data, status, headers, config, statusText) => {
                                notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                            });
                        break;
                    case 4:
                        $scope.currentSelection = "criteriaType4.tpl.htm";
                        
                        screeningToolFactory.loadCriteriaTypeFourCategories(baseCriteria.symbol).success((criteriaTypeFourCategories: ICriteriaTypeFourCategories[]) => {
                            $scope.selectedCriteria.name = baseCriteria.name;
                            $scope.selectedCriteria.type = baseCriteria.type;
                            $scope.selectedCriteria.typeFourCategories = criteriaTypeFourCategories;
                            $scope.selectedCriteria.typeFourSymbol = baseCriteria.symbol;
                            $scope.selectedCriteria.typeFourScreenOnAnyInvolvement = false;

                        }).error(data => {
                                notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(data));
                            });

                        break;
                    case 5://criteriafive
                        $scope.currentSelection = "criteriaType5.tpl.htm";
                        screeningToolFactory.loadTemplateCriteriaTypeFive(baseCriteria.id).success((criteriaTypeFive: ICriteriaTypeFive) => {
                            criteriaTypeFive.score = -1;
                            $scope.currentCriteriaTypeFive = criteriaTypeFive;

                        }).error((data, status, headers, config, statusText) => {
                                notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                            });
                        break;
                    case 6:
                        $scope.currentSelection = "criteriatypesix.tpl.htm";
                        screeningToolFactory.loadCriteriaTypeSix(baseCriteria.id).success((criteriaTypeSix: ICriteriaTypeSix) => {
                            $scope.currentCriteriaTypeSix = criteriaTypeSix;
                            $scope.criteriaTypeSixChart = {};

                            var yAxis = [];
                            $scope.criteriaTypeSixChart.xAxis = [];
                            $scope.currentCriteriaTypeSix.criteriaData.forEach(function (item) {
                                $scope.criteriaTypeSixChart.xAxis.push(item.xAxisValue);
                                yAxis.push(item.yAxisValue);
                            });


                            var data = {
                                labels: $scope.criteriaTypeSixChart.xAxis,
                                datasets: [
                                    {
                                        label: "Companies",
                                        fillColor: "rgba(220,220,220,0.5)",
                                        strokeColor: "rgba(220,220,220,0.8)",
                                        highlightFill: "rgba(220,220,220,0.75)",
                                        highlightStroke: "rgba(220,220,220,1)",
                                        data: yAxis
                                    }
                                ]
                            };

                            var options = {
                                scaleBeginAtZero: true,
                                showTooltips: false,
                                scaleShowGridLines: false,
                                scaleGridLineColor: "rgba(0,0,0,0)",
                                barValueSpacing: 7
                            };

                            $scope.criteriaTypeSixChart.minValue = $scope.criteriaTypeSixChart.xAxis[0];
                            $scope.criteriaTypeSixChart.maxValue = $scope.criteriaTypeSixChart.xAxis[$scope.criteriaTypeSixChart.xAxis.length - 1];
                            $scope.criteriaTypeSixChart.data = data;
                            $scope.criteriaTypeSixChart.options = options;
                            $scope.criteriaTypeSixChart.invalidInput = () => {
                                if (!$scope.criteriaTypeSixChart.minValue) {
                                    if ($scope.criteriaTypeSixChart.minValue != 0)
                                        return true;
                                }
                                if (!$scope.criteriaTypeSixChart.maxValue) return true;

                                var min = parseInt($scope.criteriaTypeSixChart.minValue);
                                var max = parseInt($scope.criteriaTypeSixChart.maxValue);

                                if (isNaN(min) || isNaN(max))
                                    return true;

                                var rangeMin = Math.min.apply(Math, $scope.criteriaTypeSixChart.xAxis);
                                var rangeMax = Math.max.apply(Math, $scope.criteriaTypeSixChart.xAxis);

                                if (min > max)
                                    return true;

                                if (rangeMin > min)
                                    return true;

                                if (rangeMax < max)
                                    return true;

                                return false;
                            };
                        }).error((data, status, headers, config, statusText) => {
                                notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                            });
                        break;
                    case 7:
                        $scope.currentSelection = "criteriaType7.tpl.htm";
                        screeningToolFactory.loadCriteriaTypeSeven(baseCriteria.id, 0, 20).success((criteriaTypeSeven: ICriteriaTypeSeven) => {
                            $scope.currentCriteriaTypeSeven = criteriaTypeSeven;
                            $scope.currentCriteriaTypeSeven.filter = "";
                            $scope.selectedCriteria.typeSevenSelectedItems = criteriaTypeSeven.selectedItems != null ? criteriaTypeSeven.selectedItems : [];
                            $scope.selectedCriteria.typeSevenCollectionName = criteriaTypeSeven.collectionName;

                        }).error((data, status, headers, config, statusText) => {
                                notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                            });
                        break;
                case 8:
                    $scope.currentSelection = "criteriaType8.tpl.htm";
                    $scope.selectedCriteria.typeEightScore = 0;
                    break;
                    default:
                        $scope.currentSelection = "";
                        break;
                }
            };

            $scope.getTypeSevenSelectedItemsNames = () => {
                $scope.selectedCriteria.typeSevenText = $.map($scope.selectedCriteria.typeSevenSelectedItems, (item, index) => {
                    return $scope.getTypeSevenItemName(item);
                }).join(' or ');
            };

            $scope.getTypeSevenItemName = (item: string) => {
                switch (item) {
                    case '0':
                        return 'Compliant';
                    case '1':
                        return 'Watchlist';
                    case '2':
                        return 'Non-compliant';
                }
            };

            var convertSliderValue = (value) => {
                switch (value) {
                    case 0:
                        return 0;
                        break;
                    case 1:
                        return 5;
                        break;
                    case 2:
                        return 4;
                        break;
                    case 3:
                        return 3;
                        break;
                    case 4:
                        return 2;
                        break;
                    case 5:
                        return 1;
                        break;
                    default:
                        return 0;
                }
            };

            screeningToolFactory.getCriteriaTabsAndTemplates().then(criteriaTabs=> {
                $scope.tabs = criteriaTabs;

                if (criteriaTabs != undefined && criteriaTabs.length > 0) {
                    for (var i = 0; i < criteriaTabs.length; i++) {
                        var level1 = criteriaTabs[i];
                        if (level1.isEnabled) {
                            if (level1.childItems != undefined && level1.childItems.length > 0) {
                                for (var j = 0; j < level1.childItems.length; j++) {
                                    var level2 = level1.childItems[j];
                                    if (level2.isEnabled) {
                                        if (level2.baseCriteria != undefined && level2.baseCriteria.length > 0)
                                            activateTabForBaseCriteriaName(level2.baseCriteria[0].name);

                                        return;
                                    }
                                }
                            }
                            else {
                                continue;
                            }
                        }
                        else {
                            continue;
                        }
                    }
                }
            }, error => {
                    //notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                });
            $scope.addSelectedCriteria = () => {
                setIsModified(true);
                if ($scope.selectedCriteria != null && $scope.selectedCriteria.id != null) {
                    switch ($scope.selectedCriteria.type) {
                        case 1:
                            screeningToolFactory.addCriteriaTypeOne($scope.selectedCriteria.id, $scope.criteriaTypeOneChart.minValue, $scope.criteriaTypeOneChart.maxValue)
                                .success((filterSelectedCriteria: ISelectedCriteria) => {
                                    notificationFactory.success();
                                    $("html, body").animate({
                                        scrollTop: $("#selectedCriteriaBottom").prop("clientHeight") + 100
                                    }, 500);
                                    filterSelectedCriteria.name = $scope.selectedCriteria.name;
                                    filterSelectedCriteria.type = $scope.selectedCriteria.type;
                                    filterSelectedCriteria.typeOneMinValue = $scope.criteriaTypeOneChart.minValue;
                                    filterSelectedCriteria.typeOneMaxValue = $scope.criteriaTypeOneChart.maxValue;

                                    $scope.currentFilter.selectedCriteria.push(filterSelectedCriteria);
                                    $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filterSelectedCriteria.id, filterSelectedCriteria.type, $scope.currentPortfolio.id, $scope.accountUniverseId);
                                    $scope.clearResultOutput();
                                }).error((data, status, headers, config, statusText) => {
                                    notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                                });
                            break;
                        case 2:
                            screeningToolFactory.addCriteriaTypeTwo($scope.selectedCriteria.id, convertSliderValue($scope.selectedCriteria.typeTwoScore))
                                .success((filterSelectedCriteria: ISelectedCriteria) => {
                                    notificationFactory.success();
                                    $("html, body").animate({
                                        scrollTop: $("#selectedCriteriaBottom").prop("clientHeight") + 100
                                    }, 500);

                                    filterSelectedCriteria.name = $scope.selectedCriteria.name;
                                    filterSelectedCriteria.type = $scope.selectedCriteria.type;
                                    filterSelectedCriteria.typeTwoScore = convertSliderValue($scope.selectedCriteria.typeTwoScore);

                                    $scope.currentFilter.selectedCriteria.push(filterSelectedCriteria);
                                    $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filterSelectedCriteria.id, filterSelectedCriteria.type, $scope.currentPortfolio.id, $scope.accountUniverseId);
                                    $scope.clearResultOutput();
                                }).error((data, status, headers, config, statusText) => {
                                    notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                                });
                            break;
                        case 3:
                            screeningToolFactory.addCriteriaTypeThree($scope.selectedCriteria.id, $scope.selectedCriteria.typeThreeSelectedItems)
                                .success((filterSelectedCriteria: ISelectedCriteria) => {
                                    notificationFactory.success();
                                    $("html, body").animate({
                                        scrollTop: $("#selectedCriteriaBottom").prop("clientHeight") + 100
                                    }, 500);

                                    filterSelectedCriteria.name = $scope.selectedCriteria.name;
                                    filterSelectedCriteria.type = $scope.selectedCriteria.type;
                                    filterSelectedCriteria.typeThreeSelectedItems = $scope.selectedCriteria.typeThreeSelectedItems;

                                    $scope.currentFilter.selectedCriteria.push(filterSelectedCriteria);
                                    $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filterSelectedCriteria.id, filterSelectedCriteria.type, $scope.currentPortfolio.id, $scope.accountUniverseId);
                                    $scope.clearResultOutput();
                                    $scope.selectedCriteria.typeThreeSelectedItems = [];

                                }).error((data, status, headers, config, statusText) => {
                                    notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                                });

                            break;
                        case 4:
                            var selectedCategories = [];
                            $scope.selectedCriteria.typeFourCategories.forEach((category) => {
                                if (category.isInvolved || category.isSignificantOwnership || category.selectedValue > 0) {
                                    if (category.selectedValue > 0) {
                                        selectedCategories.push(
                                            {
                                                categoryOfInvolvement: category.categoryOfInvolvement,
                                                isSignificantOwnership: false,
                                                isInvolvement: false,
                                                revenueRange: category.selectedValue > 0,
                                                start: category.revenueRange[5 - category.selectedValue].start,
                                                stop: category.revenueRange[5 - category.selectedValue].stop,
                                                name: category.name,
                                                categorySymbol: category.categorySymbol
                                            });
                                    }

                                    if (category.isInvolved) {
                                        selectedCategories.push(
                                            {
                                                categoryOfInvolvement: category.categoryOfInvolvement,
                                                isSignificantOwnership: false,
                                                isInvolvement: category.isInvolved,
                                                revenueRange: false,
                                                start: 0,
                                                stop: 0,
                                                name: category.name,
                                                categorySymbol: category.categorySymbol
                                            });
                                    }

                                    if (category.isSignificantOwnership) {
                                        selectedCategories.push(
                                            {
                                                categoryOfInvolvement: category.categoryOfInvolvement,
                                                isSignificantOwnership: category.isSignificantOwnership,
                                                isInvolvement: false,
                                                revenueRange: false,
                                                start: 0,
                                                stop: 0,
                                                name: category.name,
                                                categorySymbol: category.categorySymbol
                                            });
                                    }
                                }
                            });

                            screeningToolFactory.addCriteriaTypeFour($scope.selectedCriteria.id, selectedCategories).success((criteriaTypeFour: any) => {
                                notificationFactory.success();
                                $("html, body").animate({
                                    scrollTop: $("#selectedCriteriaBottom").prop("clientHeight") + 100
                                }, 500);

                                criteriaTypeFour.forEach((criteria) => {
                                    var filterSelectedCriteria: any = { typeFourSelectedCriteria: {} };
                                    if ($scope.selectedCriteria.typeFourSelectedCriteria != undefined)
                                        $scope.selectedCriteria.typeFourSelectedCriteria.piFilterCriteriaId = criteria.piFilterCriteriaId;
                                    filterSelectedCriteria.id = criteria.id;
                                    filterSelectedCriteria.type = $scope.selectedCriteria.type;
                                    filterSelectedCriteria.name = $scope.selectedCriteria.name;
                                    filterSelectedCriteria.typeFourSelectedCriteria.categoryOfInvolvement = criteria.piFilterCriteriaRange.categoryOfInvolvement;
                                    filterSelectedCriteria.typeFourSelectedCriteria.piFilterCriteriaId = criteria.piFilterCriteriaId;
                                    filterSelectedCriteria.typeFourSelectedCriteria.significantOwnership = criteria.piFilterCriteriaRange.significantOwnership;
                                    filterSelectedCriteria.typeFourSelectedCriteria.involvement = criteria.piFilterCriteriaRange.involvement;
                                    filterSelectedCriteria.typeFourSelectedCriteria.revenueRange = criteria.piFilterCriteriaRange.revenueRange;
                                    filterSelectedCriteria.typeFourSelectedCriteria.start = criteria.piFilterCriteriaRange.start;
                                    filterSelectedCriteria.typeFourSelectedCriteria.stop = criteria.piFilterCriteriaRange.stop;
                                    filterSelectedCriteria.typeFourSelectedCriteria.categorySymbol = criteria.piFilterCriteriaRange.categorySymbol;

                                    $scope.currentFilter.selectedCriteria.push(filterSelectedCriteria);
                                    $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filterSelectedCriteria.id, filterSelectedCriteria.type, $scope.currentPortfolio.id, $scope.accountUniverseId);
                                    
                                });

                                $scope.clearResultOutput();
                            }).error((data, status, headers, config, statusText) => {
                                    notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                            });
                            
                            break;
                        case 5://criteriafive
                            screeningToolFactory.addCriteriaTypeFive($scope.currentCriteriaTypeFive.id, $scope.currentCriteriaTypeFive.score,
                                $scope.currentCriteriaTypeFive.templateIndicatorNumber)
                                .success((filterSelectedCriteria: ISelectedCriteria) => {
                                    notificationFactory.success();
                                    $("html, body").animate({
                                        scrollTop: $("#selectedCriteriaBottom").prop("clientHeight") + 100
                                    }, 500);
                                    filterSelectedCriteria.typeFiveAnswersText = screeningToolFactory.composeAnswerTextCriteriaTypeFive(
                                        $scope.currentCriteriaTypeFive.answerCategories,
                                        $scope.currentCriteriaTypeFive.score);

                                    filterSelectedCriteria.name = $scope.selectedCriteria.name;
                                    filterSelectedCriteria.type = $scope.selectedCriteria.type;
                                    $scope.currentFilter.selectedCriteria.push(filterSelectedCriteria);
                                    $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filterSelectedCriteria.id, filterSelectedCriteria.type, $scope.currentPortfolio.id, $scope.accountUniverseId);
                                    $scope.clearResultOutput();
                                }).error((data, status, headers, config, statusText) => {
                                    notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                                });
                            break;
                        case 6:
                            screeningToolFactory.addCriteriaTypeSix($scope.selectedCriteria.id, $scope.criteriaTypeSixChart.minValue, $scope.criteriaTypeSixChart.maxValue)
                                .success((filterSelectedCriteria: ISelectedCriteria) => {
                                    notificationFactory.success();
                                    $("html, body").animate({
                                        scrollTop: $("#selectedCriteriaBottom").prop("clientHeight") + 100
                                    }, 500);

                                    filterSelectedCriteria.name = $scope.selectedCriteria.name;
                                    filterSelectedCriteria.type = $scope.selectedCriteria.type;
                                    filterSelectedCriteria.typeSixMinValue = $scope.criteriaTypeSixChart.minValue;
                                    filterSelectedCriteria.typeSixMaxValue = $scope.criteriaTypeSixChart.maxValue;

                                    $scope.currentFilter.selectedCriteria.push(filterSelectedCriteria);
                                    $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filterSelectedCriteria.id, filterSelectedCriteria.type, $scope.currentPortfolio.id, $scope.accountUniverseId);
                                    $scope.clearResultOutput();
                                }).error((data, status, headers, config, statusText) => {
                                    notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                                });
                            break;
                        case 7:
                            screeningToolFactory.addCriteriaTypeSeven($scope.selectedCriteria.id, $scope.selectedCriteria.typeSevenSelectedItems)
                                .success((filterSelectedCriteria: ISelectedCriteria) => {
                                    notificationFactory.success();
                                    $("html, body").animate({
                                        scrollTop: $("#selectedCriteriaBottom").prop("clientHeight") + 100
                                    }, 500);

                                    filterSelectedCriteria.name = $scope.selectedCriteria.name;
                                    filterSelectedCriteria.type = $scope.selectedCriteria.type;
                                    filterSelectedCriteria.typeSevenSelectedItems = $scope.selectedCriteria.typeSevenSelectedItems;

                                    $scope.getTypeSevenSelectedItemsNames();
                                    filterSelectedCriteria.typeSevenText = $scope.selectedCriteria.typeSevenText;

                                    $scope.currentFilter.selectedCriteria.push(filterSelectedCriteria);
                                    $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filterSelectedCriteria.id, filterSelectedCriteria.type, $scope.currentPortfolio.id, $scope.accountUniverseId);
                                    $scope.clearResultOutput();
                                    $scope.selectedCriteria.typeSevenSelectedItems = [];

                                }).error((data, status, headers, config, statusText) => {
                                    notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                                });

                            break;
                    case 8:
                        screeningToolFactory.addCriteriaTypeEight($scope.selectedCriteria.id, convertSliderValue($scope.selectedCriteria.typeEightScore))
                            .success((filterSelectedCriteria: ISelectedCriteria) => {
                                notificationFactory.success();
                                $("html, body").animate({
                                    scrollTop: $("#selectedCriteriaBottom").prop("clientHeight") + 100
                                }, 500);

                                filterSelectedCriteria.name = $scope.selectedCriteria.name;
                                filterSelectedCriteria.type = $scope.selectedCriteria.type;
                                filterSelectedCriteria.typeEightScore = convertSliderValue($scope.selectedCriteria.typeEightScore);

                                $scope.currentFilter.selectedCriteria.push(filterSelectedCriteria);
                                $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filterSelectedCriteria.id, filterSelectedCriteria.type, $scope.currentPortfolio.id, $scope.accountUniverseId);
                                $scope.clearResultOutput();
                            }).error((data, status, headers, config, statusText) => {
                                notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                            });
                        break;
                        default:
                            $scope.currentSelection = "";
                            break;
                    }
                }
            }

            $scope.updateSelectedCriteria = () => {
                setIsModified(true);
                if ($scope.selectedCriteria != null && $scope.selectedFilterCriteria.id != null) {
                    switch ($scope.selectedFilterCriteria.type) {
                        case 1:
                            screeningToolFactory.updateCriteriaTypeOne($scope.selectedFilterCriteria.id, $scope.criteriaTypeOneChart.minValue, $scope.criteriaTypeOneChart.maxValue)
                                .success(() => {
                                    $scope.clearResultOutput();
                                    notificationFactory.success();
                                    $scope.currentFilter.selectedCriteria.forEach((filterCriteria) => {
                                        if (filterCriteria.id == $scope.selectedFilterCriteria.id) {
                                            filterCriteria.typeOneMinValue = $scope.criteriaTypeOneChart.minValue;
                                            filterCriteria.typeOneMaxValue = $scope.criteriaTypeOneChart.maxValue;
                                            $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filterCriteria.id, filterCriteria.type, $scope.currentPortfolio.id, $scope.accountUniverseId);
                                        }
                                    });
                                }).error((data, status, headers, config, statusText) => {
                                    notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                                });
                            break;
                        case 2:
                            screeningToolFactory.updateCriteriaTypeTwo($scope.selectedFilterCriteria.id, convertSliderValue($scope.selectedCriteria.typeTwoScore))
                                .success(() => {
                                    $scope.clearResultOutput();
                                    notificationFactory.success();
                                    $scope.currentFilter.selectedCriteria.forEach((filterCriteria) => {
                                        if (filterCriteria.id == $scope.selectedFilterCriteria.id) {
                                            filterCriteria.typeTwoScore = convertSliderValue($scope.selectedCriteria.typeTwoScore);
                                            $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filterCriteria.id, filterCriteria.type, $scope.currentPortfolio.id, $scope.accountUniverseId);
                                        }
                                    });
                                }).error((data, status, headers, config, statusText) => {
                                    notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                                });
                            break;
                        case 3:
                            var criteria: ICriteriaTypeThree = {
                                collectionItems: null,
                                collectionItemsTotalCount: 0,
                                selectedItems: $scope.selectedCriteria.typeThreeSelectedItems,
                                id: $scope.selectedFilterCriteria.id,
                                type: 3,
                                name: $scope.selectedFilterCriteria.name,
                                collectionName: $scope.selectedFilterCriteria.typeThreeCollectionName,
                                filter: "",
                                isActive: false,
                                isEnabled: true,
                                symbol: ""
                            }
                            screeningToolFactory.updateCriteriaTypeThree(criteria)
                                .success(() => {
                                    $scope.clearResultOutput();
                                    notificationFactory.success();
                                    $scope.currentFilter.selectedCriteria.forEach((filterCriteria) => {
                                        if (filterCriteria.id == $scope.selectedFilterCriteria.id) {
                                            filterCriteria.typeThreeSelectedItems = $scope.selectedCriteria.typeThreeSelectedItems;
                                            $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filterCriteria.id, filterCriteria.type, $scope.currentPortfolio.id, $scope.accountUniverseId);
                                        }
                                    });
                                }).error((data, status, headers, config, statusText) => {
                                    notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                                });
                            break;
                        case 4: 

                            var indexes: number[] = [];

                            for (var i = 0; i < $scope.currentFilter.selectedCriteria.length; i++) {
                                if ($scope.currentFilter.selectedCriteria[i].type != 4) {
                                    indexes.push(i);
                                    continue;
                                }

                                var sCriteria = $scope.currentFilter.selectedCriteria[i];
                                if (sCriteria.typeFourSelectedCriteria.piFilterCriteriaId != $scope.selectedCriteria.typeFourSelectedCriteria.piFilterCriteriaId) {
                                    indexes.push(i);
                                }
                            }

                            var tempSelectedCriteria = []
                            indexes.forEach((index) => {
                                tempSelectedCriteria.push($scope.currentFilter.selectedCriteria[index]);
                            });
                            $scope.currentFilter.selectedCriteria = tempSelectedCriteria;
                            screeningToolFactory.deleteCriteriaTypeFour($scope.selectedCriteria.typeFourSelectedCriteria.piFilterCriteriaId);
                            $scope.addSelectedCriteria();

                            break;
                        case 5://criteriafive
                            screeningToolFactory.updateCriteriaTypeFive($scope.currentCriteriaTypeFive.id, $scope.currentCriteriaTypeFive.score, $scope.currentCriteriaTypeFive.templateIndicatorNumber)
                                .success(() => {
                                    $scope.clearResultOutput();
                                    notificationFactory.success();
                                    $scope.currentFilter.selectedCriteria.forEach((filterCriteria) => {
                                        if (filterCriteria.id == $scope.selectedFilterCriteria.id) {

                                            filterCriteria.typeFiveAnswersText = $scope.currentCriteriaTypeFive.answerText;
                                            $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filterCriteria.id, filterCriteria.type, $scope.currentPortfolio.id, $scope.accountUniverseId);
                                        }
                                    });
                                }).error((data, status, headers, config, statusText) => {
                                    notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                                });
                            break;
                        case 6:
                            screeningToolFactory.updateCriteriaTypeSix($scope.selectedFilterCriteria.id, $scope.criteriaTypeSixChart.minValue, $scope.criteriaTypeSixChart.maxValue)
                                .success(() => {
                                    $scope.clearResultOutput();
                                    notificationFactory.success();
                                    $scope.currentFilter.selectedCriteria.forEach((filterCriteria) => {
                                        if (filterCriteria.id == $scope.selectedFilterCriteria.id) {
                                            filterCriteria.typeSixMinValue = $scope.criteriaTypeSixChart.minValue;
                                            filterCriteria.typeSixMaxValue = $scope.criteriaTypeSixChart.maxValue;
                                            $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filterCriteria.id, filterCriteria.type, $scope.currentPortfolio.id, $scope.accountUniverseId);
                                        }
                                    });
                                }).error((data, status, headers, config, statusText) => {
                                    notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                                });
                            break;
                        case 7:
                            var criteria: ICriteriaTypeSeven = {
                                collectionItems: null,
                                collectionItemsTotalCount: 0,
                                selectedItems: $scope.selectedCriteria.typeSevenSelectedItems,
                                id: $scope.selectedFilterCriteria.id,
                                type: 7,
                                name: $scope.selectedFilterCriteria.name,
                                collectionName: $scope.selectedFilterCriteria.typeSevenCollectionName,
                                filter: "",
                                isActive: false,
                                isEnabled: true,
                                symbol: ""
                            }
                            screeningToolFactory.updateCriteriaTypeSeven(criteria)
                                .success(() => {
                                    $scope.clearResultOutput();
                                    notificationFactory.success();
                                    $scope.currentFilter.selectedCriteria.forEach((filterCriteria) => {
                                        if (filterCriteria.id == $scope.selectedFilterCriteria.id) {
                                            filterCriteria.typeSevenSelectedItems = $scope.selectedCriteria.typeSevenSelectedItems;

                                            $scope.getTypeSevenSelectedItemsNames();
                                            filterCriteria.typeSevenText = $scope.selectedCriteria.typeSevenText;

                                            $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filterCriteria.id, filterCriteria.type, $scope.currentPortfolio.id, $scope.accountUniverseId);

                                            $scope.selectedCriteria.typeSevenSelectedItems = [];
                                        }
                                    });
                                }).error((data, status, headers, config, statusText) => {
                                    notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                                });
                            break;
                    case 8:
                        screeningToolFactory.updateCriteriaTypeEight($scope.selectedFilterCriteria.id, convertSliderValue($scope.selectedCriteria.typeEightScore))
                            .success(() => {
                                $scope.clearResultOutput();
                                notificationFactory.success();
                                $scope.currentFilter.selectedCriteria.forEach((filterCriteria) => {
                                    if (filterCriteria.id == $scope.selectedFilterCriteria.id) {
                                        filterCriteria.typeEightScore = convertSliderValue($scope.selectedCriteria.typeEightScore);
                                        $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filterCriteria.id, filterCriteria.type, $scope.currentPortfolio.id, $scope.accountUniverseId);
                                    }
                                });
                            }).error((data, status, headers, config, statusText) => {
                                notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                            });
                        break;
                        default:
                            $scope.currentSelection = "";
                            break;
                    }
                }
                $scope.selectedCriteria.loading = false;
            };
            $scope.deleteSelectedItems = (item) => {
                var index = $scope.selectedCriteria.typeThreeSelectedItems.indexOf(item);
                if (index != -1) {
                    $scope.selectedCriteria.typeThreeSelectedItems.splice(index, 1);
                }
            };
            $scope.deleteCriteriaTypeSevenSelectedItems = (item) => {
                var index = $scope.selectedCriteria.typeSevenSelectedItems.indexOf(item);
                if (index != -1) {
                    $scope.selectedCriteria.typeSevenSelectedItems.splice(index, 1);
                }

                buildGcSelectedItemsText();
            };
            $scope.addItemToSelectedItems = (item) => {

                var index = $scope.selectedCriteria.typeThreeSelectedItems.indexOf(item);
                if (index == -1) {
                    $scope.selectedCriteria.typeThreeSelectedItems.push(item);
                }
            };

            

            $scope.addCriteriaTypeSevenItemToSelectedItems = (item) => {

                var index = $scope.selectedCriteria.typeSevenSelectedItems.indexOf(item);
                if (index == -1) {
                    $scope.selectedCriteria.typeSevenSelectedItems.push(item);
                }
                buildGcSelectedItemsText();
            };

            buildGcSelectedItemsText = () => {
                $scope.gcSelectedItems = '';
                for (var i = 0; i < $scope.selectedCriteria.typeSevenSelectedItems.length; i++) {

                    var selectedItem = $scope.getTypeSevenItemName($scope.selectedCriteria.typeSevenSelectedItems[i]);

                    $scope.gcSelectedItems += selectedItem + ' ';

                    if (i + 1 < $scope.selectedCriteria.typeSevenSelectedItems.length) {
                        $scope.gcSelectedItems += ' and ';
                    }
                }

                $scope.gcSelectedItems += ' companies are excluded.';
            };

            $scope.loadCriteriaTypeThreeCollectionItems = (loadMore) => {
                var skip = 0;
                if (loadMore) {
                    skip = $scope.currentCriteriaTypeThree.collectionItems.length;
                }
                screeningToolFactory.getCriteriaTypeThreeCollectionItems($scope.selectedCriteria.id, $scope.currentCriteriaTypeThree.filter, loadMore, skip, 20)
                    .success((criteriaTypeThree: ICriteriaTypeThree) => {
                        notificationFactory.success();
                        if (loadMore) {
                            var newItems = $scope.currentCriteriaTypeThree.collectionItems;
                            newItems.push.apply(newItems, criteriaTypeThree.collectionItems);
                            $scope.currentCriteriaTypeThree.collectionItems = newItems;
                        } else {
                            $scope.currentCriteriaTypeThree.collectionItems = criteriaTypeThree.collectionItems;
                        }
                        $scope.currentCriteriaTypeThree.collectionItemsTotalCount = criteriaTypeThree.collectionItemsTotalCount;

                    }).error((data, status, headers, config, statusText) => {
                        notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                    });
            };
            $scope.loadCriteriaTypeSevenCollectionItems = (loadMore) => {
                var skip = 0;
                if (loadMore) {
                    skip = $scope.currentCriteriaTypeSeven.collectionItems.length;
                }
                screeningToolFactory.getCriteriaTypeSevenCollectionItems($scope.selectedCriteria.id, $scope.currentCriteriaTypeSeven.filter, loadMore, skip, 20)
                    .success((criteriaTypeSeven: ICriteriaTypeSeven) => {
                        notificationFactory.success();
                        if (loadMore) {
                            var newItems = $scope.currentCriteriaTypeSeven.collectionItems;
                            newItems.push.apply(newItems, criteriaTypeSeven.collectionItems);
                            $scope.currentCriteriaTypeSeven.collectionItems = newItems;
                        } else {
                            $scope.currentCriteriaTypeSeven.collectionItems = criteriaTypeSeven.collectionItems;
                        }
                        $scope.currentCriteriaTypeSeven.collectionItemsTotalCount = criteriaTypeSeven.collectionItemsTotalCount;

                    }).error((data, status, headers, config, statusText) => {
                        notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                    });
            };

            $scope.runCurrentCriteria = () => {
                $scope.selectedCriteriaIsrunning = true;
                var promise = $scope.runCriteria($scope.currentFilter.filterId);
                promise.then(function () {
                    notificationFactory.success("All criteria processed");
                    $scope.selectedCriteriaIsrunning = false;
                });

                return promise;
            };



            $scope.exportCriteria = () => {
                //var promise = screeningToolFactory.exportCurrentCriteria(exportDetails);

                //return promise;

                var modalInstance = $modal.open({
                    templateUrl: 'exportCriteria_dialog.tpl.html',
                    controller: 'ExportCurrentCriteriaResults',
                    size: 'lg',
                    backdrop: 'static',
                    resolve: {
                        options: function () {
                            return { baseCriteriaList: $scope.baseCriteriaList, currentFilter: $scope.currentFilter }
                        }
                    }
                });

                modalInstance.result.then((item) => {
                    console.log(item.name);
                    //$scope.currentFilter.name = item.name;
                    //$scope.currentFilter.shared = item.shared;
                    //setIsModified(false);
                });
            }

            $scope.runCriteria = (filterId) => {
                var def = $q.defer();

                $rootScope['loading'] = true;
                var promise = undefined;

                if ($rootScope['screeningExportDetails'].SelectedPortfolio != undefined)
                    promise = screeningToolFactory.runSelectedCriteria(filterId, $rootScope['screeningExportDetails'].SelectedPortfolio.id);
                else
                
                    promise = screeningToolFactory.runSelectedCriteria(filterId, "00000000-0000-0000-0000-000000000000");

                promise.then(() => {
                    // reset order criteria
                    $scope.resultOutputFilter.isValid = null;
                    $scope.resultOutputFilter.isValidEnabled = true;
                    $scope.resultOutputFilter.isNotValidEnabled = true;
                    $scope.resultOutputOrderBy = "CompanyNameLowerCase";
                    $scope.resultOutputOrderByAscending = true;

                    $scope.getResultOutput(1)
                        .then(function () {
                            $rootScope['loading'] = false;

                            def.resolve();
                        })
                    ['catch'](function () {
                            $rootScope['loading'] = false;

                            def.reject();
                        });
                });
                promise.error((data, status, headers, config) => {
                    notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                    def.reject();
                });

                return def.promise;
            };


            //$scope.processedCriteria = [];
            //var nrOfPages = () => Math.ceil($scope.totalRecords / $scope.pageSize);
            //var skipItems = (): number => ($scope.currentPage - 1) * $scope.pageSize;
            //$scope.totalRecords = 0;
            //$scope.pageSize = 20;
            //$scope.currentPage = 1;
            //$scope.changePageSize = () => {
            //    $scope.currentPage = 1;

            //    $scope.getResultOutput($scope.currentFilter.filterId, $scope.pageSize, skipItems());
            //};
            //$scope.range = () => {

            //    var ret = [];

            //    for (var i = 1; i <= nrOfPages(); i++) {
            //        ret.push(i);
            //    }
            //    return ret;
            //};
            //$scope.displayedItems = () => (skipItems() + 1) + " - " + (skipItems() + $scope.processedCriteria.length);

            //$scope.prevPage = () => {
            //    if ($scope.currentPage > 1) {
            //        $scope.currentPage--;
            //        $scope.getResultOutput($scope.currentFilter.filterId, $scope.pageSize, skipItems());
            //    }
            //};

            //$scope.nextPage = () => {
            //    if ($scope.currentPage < nrOfPages()) {
            //        $scope.currentPage++;
            //        $scope.getResultOutput($scope.currentFilter.filterId, $scope.pageSize, skipItems());
            //    }
            //};

            //$scope.setPage = function () {
            //    $scope.currentPage = this.n;
            //    $scope.getResultOutput($scope.currentFilter.filterId, $scope.pageSize, skipItems());
            //};


            $scope.refreshResultOutputs = () => {
                return $scope.runCriteria($scope.currentFilter.filterId);
                //$scope.currentFilter.selectedCriteria.length = 0;
                //$scope.resultOutputPaged = null;
                //var pager: Pager.PagerController = $scope['pager'];
                //pager.totalItemsCount = 0;
            };

            $scope.deleteAllCriteria = (filterId) => {
                var def = $q.defer();

                if (!confirm("Are you sure you want to clear all criteria?")) {
                    def.reject();
                    return def.promise;
                }

                setIsModified(true);

                var promise = screeningToolFactory.deleteAllCriteria(filterId)
                    .success(() => {
                        $scope.currentFilter.selectedCriteria = new Array();
                        notificationFactory.success("All criteria cleared");
                    $scope.clearResultOutput().then(function () { def.resolve(); })['catch'](function () { def.reject(); });
                    }).error((data, status, headers, config, statusText) => {
                        notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                        def.reject();
                    });

                return def.promise;
            };

            $scope.clearResultOutput = () => {
                var filterId = $scope.currentFilter.filterId;
                var def = $q.defer();
                var promise: ng.IPromise<{}> = screeningToolFactory.deleteResultOutput(filterId);
                promise.then(function () {
                    var pager: Sustainalytics.Pager.PagerController = $scope['pager'];
                    $scope.resultOutputPaged = null;
                    pager.totalItemsCount = 0;
                    def.resolve();
                    //$scope.getResultOutput(1)
                    //    .then(function () {
                    //        def.resolve();
                    //    })
                //    ['catch'](function () {
                    //        def.reject();
                    //    });
                });
                return def.promise;
            };

            $scope.open = (size) => {
                var modalInstance = $modal.open({
                    templateUrl: 'loadFilterSelect_dialog.tpl.html',
                    controller: 'LoadFilterSelectModalController',
                    size: size || 'lg',
                    backdrop: 'static',
                    resolve: {
                        options: function () {
                            var requiresConfirmation = false;
                            if ($scope.currentFilter && $scope.currentFilter.isModified) {
                                requiresConfirmation = true;
                            }

                            return { requiresConfirmation: requiresConfirmation };
                        }
                    }
                });

                modalInstance.result.then((item) => {
                    if (item.filterId === '00000000-0000-0000-0000-000000000000')
                        $scope.loadStandardFilter(StandardFilter.StandardFilter, false);
                    else
                          $scope.loadSavedFilter(item, false);
                });
            };
            $scope.asyncLoadFiltersOperation = new Sustainalytics.Common.AsyncHttpOperation();

            var loadLatestFiltes = function () {
                if ($scope.asyncLoadFiltersOperation.executing) {
                    return;
                }
                $scope.asyncLoadFiltersOperation.execute(screeningToolFactory.listLastUsedFilters)
                    .then(
                    (response: ng.IHttpPromiseCallbackArg<any>) => { $scope.lastUsedFilters = response.data; },
                    (response: ng.IHttpPromiseCallbackArg<Common.IErrorDto<any>>) => {
                        $scope.lastUsedFilters = null;
                        notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(response.status, response.data));
                    }
                    );
            }

            $scope.ensureLatestFilters = function (open) {
                if (!open) {
                    return;
                }
                if (!$scope.lastUsedFilters) {
                    loadLatestFiltes();
                }
            };

            $scope.openSavePortfolio = function () {
                var ctx = this;
                var modalInstance = $modal.open(
                    {
                        templateUrl: '/Views/Portfolio/savePortfolioScreeningDialog.tpl.html',
                        controller: 'PortfolioAddController',
                        size: 'lg',
                        backdrop: 'static',
                        resolve: {
                            filterId: function () {
                                return ctx.currentFilter.filterId;
                        },
                        companyId: function () {
                            return null;
                            }
                        }
                    });

                modalInstance.result.then((item) => {
                    //$scope.currentFilter.name = item.name;
                    //$scope.currentFilter.shared = item.shared;
                    //setIsModified(false);
                });
            };

            $scope.saveFilter = function (saveNew) {
                var modalInstance = $modal.open({
                    templateUrl: 'saveFilter_dialog.tpl.html',
                    controller: 'SaveFilterModalController',
                    size: 'lg',
                    backdrop: 'static',
                    resolve: {
                        options: function () {
                            if (saveNew) {
                                return { createNew: saveNew, name: "", shared: false };
                            }
                            return { createNew: saveNew, name: $scope.currentFilter.name, shared: $scope.currentFilter.shared };
                        }
                    }

                });

                modalInstance.result.then((item) => {
                    if (!saveNew) {
                        $scope.currentFilter.name = item.name;
                        $scope.currentFilter.shared = item.shared;
                        setIsModified(false);
                    }
                    else {
                        $scope.loadSavedFilter(item, false);
                    }
                });
            };

            var loadSavedFilter = (rootFilterId: string) => {
                return screeningToolFactory.loadSavedFilter(rootFilterId);
            };
            var loadStandardFilter = (standardFilterType: StandardFilter) => {
                return screeningToolFactory.loadStandardFilter(standardFilterType);
            };
            // Standard Filter
            $scope.asyncLoadStandardFilter = new Sustainalytics.Common.AsyncHttpOperation();


            $scope.loadStandardFilter = (standardFilterType: StandardFilter, requiresConfirmation: boolean) => {
                ///load selected filter
                if ($scope.asyncLoadSavedFilter.executing) {
                    return;
                }
                $scope.isLatestDropDownOpen = false;

                if (!(requiresConfirmation === false)) {
                    if ($scope.currentFilter) {
                        if ($scope.currentFilter.isModified) {
                            if (!confirm("This will overwrite your current criteria selection. Are you sure you want to continue?")) {
                                return;
                            }
                        }
                    }
                }

                $scope.asyncLoadSavedFilter.execute(() => loadStandardFilter(StandardFilter.StandardFilter))
                    .then((response: ng.IHttpPromiseCallbackArg<IScreeningToolFilter>) => {
                        notificationFactory.success('Filter "' + response.data.name + '" loaded.');
                        var item = response.data;
                        if (item) {
                            if ($scope.lastUsedFilters === null) {
                                $scope.lastUsedFilters = [];
                                $scope.lastUsedFilters.push(item);
                            }
                            else {
                                var foundIndex = -1;
                                angular.forEach($scope.lastUsedFilters, (filter, index) => {
                                    if (filter && item.rootFilterId === filter.rootFilterId) {
                                        foundIndex = index;
                                    }
                                });

                                if (foundIndex > 0) {
                                    $scope.lastUsedFilters.splice(foundIndex, 1);
                                }
                                if (foundIndex != 0) {
                                    $scope.lastUsedFilters.splice(0, 0, item);
                                }
                                if ($scope.lastUsedFilters.length > 5) {
                                    $scope.lastUsedFilters.pop();
                                }
                            }
                        }

                        $scope.applyCurrentFilter(response.data);

                    },
                    (response: ng.IHttpPromiseCallbackArg<Common.IErrorDto<any>>) => {
                        notificationFactory.error("Failed to loaded the selected filter.", staticObjects.getErrorMesageByStatusCode(response.status, response.data));
                    }
                    );
            }
            //

            $scope.asyncLoadSavedFilter = new Sustainalytics.Common.AsyncHttpOperation();


            $scope.loadSavedFilter = (requestLoadFilter: IFilter, requiresConfirmation: boolean) => {
                ///load selected filter
                if ($scope.asyncLoadSavedFilter.executing) {
                    return;
                }
                $scope.isLatestDropDownOpen = false;

                if (!(requiresConfirmation === false)) {
                    if ($scope.currentFilter) {
                        if ($scope.currentFilter.isModified) {
                            if (!confirm("This will overwrite your current criteria selection. Are you sure you want to continue?")) {
                                return;
                            }
                        }
                    }
                }

                $scope.asyncLoadSavedFilter.execute(() => loadSavedFilter(requestLoadFilter.rootFilterId))
                    .then((response: ng.IHttpPromiseCallbackArg<IScreeningToolFilter>) => {
                        notificationFactory.success('Filter "' + response.data.name + '" loaded.');
                        var item = response.data;
                        if (item) {
                            if ($scope.lastUsedFilters === null || $scope.lastUsedFilters == undefined) {
                                $scope.lastUsedFilters = [];
                                $scope.lastUsedFilters.push(item);
                            }
                            else {
                                var foundIndex = -1;
                                angular.forEach($scope.lastUsedFilters, (filter, index) => {
                                    if (filter && item.rootFilterId === filter.rootFilterId) {
                                        foundIndex = index;
                                    }
                                });

                                if (foundIndex > 0) {
                                    $scope.lastUsedFilters.splice(foundIndex, 1);
                                }
                                if (foundIndex != 0) {
                                    $scope.lastUsedFilters.splice(0, 0, item);
                                }
                                if ($scope.lastUsedFilters.length > 5) {
                                    $scope.lastUsedFilters.pop();
                                }
                            }
                        }

                        $scope.applyCurrentFilter(response.data);

                    },
                    (response: ng.IHttpPromiseCallbackArg<Common.IErrorDto<any>>) => {
                        notificationFactory.error("Failed to loaded the selected filter.", staticObjects.getErrorMesageByStatusCode(response.status, response.data));
                    }
                    );
            }
            $scope.openFilterContainer = () => {
                if (!$scope.resultOutputPaged) {
                    return;
                }
                if ($scope.resultOutputIsValidVisible == true) {
                    $scope.resultOutputIsValidVisible = false;
                } else {
                    $scope.resultOutputIsValidVisible = true;
                }
            }
            $scope.hideFilterContainer = () => {
                $scope.resultOutputIsValidVisible = false;
            }
        }
    };

    
    interface ILoadFilterSelectModalScope extends ng.IScope {
        cancel: () => void;
        selectItem: (item) => void;
        asyncLoadFiltersOperation: Sustainalytics.Common.AsyncHttpOperation<any>;
        filterGroups: any;

        checkSortBy: (column: string, direction: boolean) => boolean;
        orderby: string;
        descending: boolean;
        setOrder: (columns: string) => void;

    };


    class LoadFilterSelectModalController {
        constructor(private $scope: ILoadFilterSelectModalScope, $rootScope, notificationFactory: Common.INotificationFactory, staticObjects: Common.IStaticObjects, screeningToolFactory: IScreeningToolFactory, $modalInstance: Common.IModalInstance, options: any) {

            $scope.orderby = "stats.lastUsed";
            $scope.descending = true;
            $scope.filterGroups = [
                { "name": "Standard Filters", "filters": null},
                { "name": "My Filters", "filters": null },
                { "name": "Shared Filters", "filters": null }
            ];

            $scope.asyncLoadFiltersOperation = new Sustainalytics.Common.AsyncHttpOperation();

            var loadFilters = () => {
                $scope.asyncLoadFiltersOperation.execute(screeningToolFactory.listUserFilters).then(
                    (response: ng.IHttpPromiseCallbackArg<IUserFiltersDto>) => {
                        var data = <IUserFiltersDto>response;
                        
                        /// add standard filters
                        $scope.filterGroups[0].filters = data.filters.filter((f) => { return f.filter && f.filter.filterType === FilterType.Standard });
                        /// add my filters
                        $scope.filterGroups[1].filters = data.filters.filter((f) => { return f.filter && f.filter.ownerUserId === data.userId && f.filter.filterType !== FilterType.Standard; });
                        /// add shared filters
                        $scope.filterGroups[2].filters = data.filters.filter((f) => { return f.filter && f.filter.ownerUserId !== data.userId && f.filter.filterType !== FilterType.Standard; });
                    },
                    (response: ng.IHttpPromiseCallbackArg<Common.IErrorDto<any>>) => {
                        notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(response.status, response.data));
                    }
                );
            };

            $scope.cancel = () => {
                $modalInstance.dismiss('cancel');
            };


            $scope.selectItem = item => {

                if (options.requiresConfirmation) {
                    if (!confirm("This will overwrite your current criteria selection. Are you sure you want to continue?")) {
                        return;
                    }
                }
                $modalInstance.close(item);
            };

            $scope.setOrder = (orderby) => {
                if (orderby === $scope.orderby) {
                    $scope.descending = !$scope.descending;
                } else {
                    if (orderby === "stats.lastUsed" || orderby === "stats.lastSaved") {
                        $scope.descending = true;
                    } else {
                        $scope.descending = false;
                    }

                }

                $scope.orderby = orderby;
            };

            $scope.checkSortBy = (value, ascending) => {
                return $scope.orderby === value && $scope.descending === !ascending;
            };

            loadFilters();
        }
    };


    interface ISaveFilterModalScope extends ng.IScope {
        saveNew: boolean;
        filter: any;

        save: () => any;
        cancel: () => any;
        asyncSaveOperation: Sustainalytics.Common.AsyncHttpOperation<any>;
        form: any;
        submitted: boolean;
        errors: any;
        switchShared: () => void;
        acceptAccessConfirmation: boolean;
        requiresConfirmation: boolean;
        requiresOverwriteConfirmation: boolean;
        validateAccept: () => any;
        errorMessage: string;
        unacceptedName: boolean;
    };


    class SaveFilterModalController {
        private serverErrors = {
            validationError: 1040
        }
        constructor(private $scope: ISaveFilterModalScope, $rootScope, notificationFactory: Common.INotificationFactory, staticObjects: Common.IStaticObjects, screeningToolFactory: IScreeningToolFactory, $modalInstance: Common.IModalInstance, options: any) {
            var requiresConfirmation = (!options.createNew) && (options.shared);
            var validationErrors =
                {
                    4002: { field: "name", message: "A filter by this name already exists, please enter a unique name and press save." },
                    4001: { field: "name", message: "A filter by this name already exists, please enter a unique name and press save." },
                    4003: { field: "name", message: "The filter's name is required." },
                    4004: { filed: "name", message: "A filter name cannot be the same as a Standard Filter."}
                };
            $scope.form = {};
            $scope.submitted = false;
            $scope.errors = {};
            $scope.saveNew = options.createNew;
            $scope.filter = { originalName: options.name, name: options.name, shared: options.shared, acceptAccessConfirmation: false, filterId: null, acceptOverwrite: false };

            $scope.requiresConfirmation = (requiresConfirmation && !$scope.filter.shared);
            $scope.acceptAccessConfirmation = false;
            $scope.requiresOverwriteConfirmation = !options.createNew && options.name;


            var saveOperation = () => {
                if ($scope.saveNew) {
                    return screeningToolFactory.saveNewFilter($scope.filter);
                }

                return screeningToolFactory.saveFilter($scope.filter);
            };

            $scope.asyncSaveOperation = new Sustainalytics.Common.AsyncHttpOperation();

            $scope.switchShared = () => {
                var shared = !$scope.filter.shared;
                $scope.filter.shared = shared;
                $scope.requiresConfirmation = requiresConfirmation && !shared;
                $scope.filter.acceptAccessConfirmation = false;
                //$scope.form.filter.acceptAccessConfirmation.$setValidity("required", $scope.requiresConfirmation);
            };

            $scope.validateAccept = () => {
                $scope.form.filter.acceptAccessConfirmation.$setValidity("required", false);
            };

            $scope.save = () => {
                $scope.errorMessage = null;
                $scope.submitted = true;

                if (!$scope.filter.name) {
                    return;
                }

                if ($scope.requiresConfirmation && (!$scope.filter.acceptAccessConfirmation)) {
                    return;
                }

                if ($scope.requiresOverwriteConfirmation && (!$scope.filter.acceptOverwrite)) {
                    return;
                }

                if ($scope.asyncSaveOperation.executing) {
                    return;
                }

                if ($scope.filter.name === "Relative Analysis") {
                    $scope.unacceptedName = true;
                    return;
                }

                if ($scope.filter.name === "relative analysis") {
                    $scope.unacceptedName = true;
                    return;
                }

                $scope.asyncSaveOperation.execute(saveOperation).then(
                    (response: ng.IHttpPromiseCallbackArg<any>) => {
                        $scope.filter.rootFilterId = response.data.rootFilterId;
                        var data = response.data;
                        notificationFactory.success("Save filter operation executed successfully.");
                        $modalInstance.close($scope.filter);
                    },
                    (response: ng.IHttpPromiseCallbackArg<Common.IErrorDto<IFilterValidationDto>>) => {

                        if (response && response.data && response.data.errorStatusCode === this.serverErrors.validationError
                                && response.data.details && response.data.details.filterValidationError
                        ) {
                            var validationErrorCode = response.data.details.filterValidationError;
                            var errorEntry = validationErrors[validationErrorCode];
                            if (errorEntry) {
                                $scope.form.filter[errorEntry.field].$setValidity("server", false);
                                $scope.errors[errorEntry.field] = errorEntry.message;
                                return;
                            }
                        }

                        var message = staticObjects.getErrorMesageByStatusCode(response.status, response.data);
                        $scope.errorMessage = message;
                        //notificationFactory.error(message, "Error");
                    }
                );
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }
    };

    interface IExportCurrentCriteriaResults extends ng.IScope {
        getTypeSixCriterias: () => any;
        getTypeThreeCriterias: () => any;
        getTypeSevenCriterias: () => any;
        getExtraFilters: () => any;
        getTypeFiveCriterias: () => any;
        exportCurrentCriteria: (boolean) => any;
        getCheckedState: (string) => any;
        CheckInCurrentCriteria: (ISelectedCriteria, IBaseCriteria) => boolean;
        resetAll: () => void;

        ModifyExtraDetails: (string) => any;

        typeSix: Array<ExportDetailsFilter>;
        typeThree: Array<ExportDetailsFilter>;
        typeSeven: Array<ExportDetailsFilter>;
        typeFive: Array<IndicatorOptions>;
        indicatorOptions: boolean;
        close: () => void;
    }

    class ExportCurrentCriteriaResults {
        constructor(private $scope: IExportCurrentCriteriaResults, $rootScope, staticObjects: Common.IStaticObjects, screeningToolFactory: IScreeningToolFactory, $modelInstance: Common.IModalInstance, options: any, LongRunningTaskManagerService: Sustainalytics.LRTM.LongRunningTaskManagerService) {

            $scope.getTypeSixCriterias = () => {

                var baseCriteriaList = options.baseCriteriaList;

                var currentFilter = options.currentFilter.selectedCriteria;

                $scope.typeSix = new Array<ExportDetailsFilter>();

                $.each(baseCriteriaList, (index: number, value: IBaseCriteria) => {
                    if (value.type == 6) {
                        var exportDetailsFilter = new ExportDetailsFilter();

                        exportDetailsFilter.baseCriteriaList = value;

                        exportDetailsFilter.isDisabled = $scope.CheckInCurrentCriteria(currentFilter, value);

                        $scope.CheckInCurrentCriteria(currentFilter, value);

                        $scope.typeSix.push(exportDetailsFilter);
                    }
                });
            }

            $scope.getCheckedState = (checkBoxName: string) => {
                var state = false;
                switch (checkBoxName) {
                    // Company Info Extras
                case "Peer Group name":
                    return $rootScope['screeningExportDetails'].PeerGroup;
                case "Region":
                    return $rootScope['screeningExportDetails'].Region = $rootScope['screeningExportDetails'].Region;
                case "Country":
                    return $rootScope['screeningExportDetails'].Country = $rootScope['screeningExportDetails'].Country;
                case "Market Capitalization":
                    return $rootScope['screeningExportDetails'].MarketCapitalization = $rootScope['screeningExportDetails'].MarketCapitalization;
                case "Sedol":
                    return $rootScope['screeningExportDetails'].Sedol = $rootScope['screeningExportDetails'].Sedol;

                // ESG Performance
                case "Total ESG Score":
                    return $rootScope['screeningExportDetails'].TotalEsgScore;
                case "Environment Score":
                    return $rootScope['screeningExportDetails'].EnvironmentScore;
                case "Social Score":
                    return $rootScope['screeningExportDetails'].SocialScore;
                case "Governance Score":
                    return $rootScope['screeningExportDetails'].GovernanceScore;
                case "Preparedness Score":
                    return $rootScope['screeningExportDetails'].PreparednessScore;
                case "Disclosure Score":
                    return $rootScope['screeningExportDetails'].DisclosureScore;
                case "Quantitative Performance Score":
                    return $rootScope['screeningExportDetails'].QualitativePerformanceScore;
                case "Qualitative Performance Score":
                    return $rootScope['screeningExportDetails'].QuantitativePerformanceScore;

                // Standard Indicators
                case "AnswerCategory":
                    return $rootScope['screeningExportDetails'].StandardIndicatorAnswerCategories;
                case "RawScore":
                    return $rootScope['screeningExportDetails'].StandardIndicatorRawScores;
                case "WeightedScore":
                    return $rootScope['screeningExportDetails'].StandardIndicatorWeights;
                default:
                    break;
                }
            }
            $scope.getTypeFiveCriterias = () => {
                var baseCriteriaList = options.baseCriteriaList;

                var currentFilter = options.currentFilter.selectedCriteria;

                $scope.typeFive = new Array<IndicatorOptions>();

                var indicatorOptionsList = new Array<string>();

                indicatorOptionsList.push('AnswerCategory');
                indicatorOptionsList.push('RawScore');
                indicatorOptionsList.push('WeightedScore');

                for (var i = 0; i < indicatorOptionsList.length; i++) {
                    var indicatorOptions = new IndicatorOptions();

                    indicatorOptions.name = indicatorOptionsList[i];
                    indicatorOptions.isDisabled = false;

                    $scope.typeFive.push(indicatorOptions);
                }

                $.each(currentFilter, (index: number, value: ISelectedCriteria) => {
                    if (value.type == 5) {
                        $scope.indicatorOptions = true;
                        
                        return;
                    }
                });


            }

            $scope.getTypeThreeCriterias = () => {

                var baseCriteriaList = options.baseCriteriaList;
                var currentFilter = options.currentFilter.selectedCriteria;

                $scope.typeThree = new Array<ExportDetailsFilter>();
                $.each(baseCriteriaList, (index: number, value: IBaseCriteria) => {

                    if ((value.type == 3) && (
                        value.name == "Peer Group name" || // c357e4f0-a840-4df2-fa4e-1099024a7680 Peer Group Name
                            value.name == "Region" || // d0d36a30-844f-40d2-5d04-91b3aff5a776 Region
                            value.name == "Country" || // 9e6c1f08-b407-4660-2b95-5a5b0aa540fe Country
                            value.name == "Sedol")) // 7c713e99-c525-480f-ba32-cd79fcb855dc Sedol
                    {
                        var exportDetailsFilter = new ExportDetailsFilter();

                        exportDetailsFilter.baseCriteriaList = value;

                        exportDetailsFilter.isDisabled = $scope.CheckInCurrentCriteria(currentFilter, value);

                        $scope.typeThree.push(exportDetailsFilter);
                    }

                    if ((value.type == 1) && (value.id == "Market Capitalization")) // 66a14c85-5e13-463e-f898-55318c447ff1 Market Cap.
                    {
                        var exportDetailsFilter = new ExportDetailsFilter();

                        exportDetailsFilter.baseCriteriaList = value;

                        exportDetailsFilter.isDisabled = $scope.CheckInCurrentCriteria(currentFilter, value);

                        $scope.typeThree.push(exportDetailsFilter);
                    }

                });

                if (!$rootScope['screeningExportDetails'].StandardIndicatorAnswerCategories &&
                    !$rootScope['screeningExportDetails'].StandardIndicatorWeights &&
                    !$rootScope['screeningExportDetails'].StandardIndicatorRawScores)
                    $rootScope['screeningExportDetails'].StandardIndicatorAnswerCategories = true;
            }

            $scope.getTypeSevenCriterias = function () {

                var baseCriteriaList = options.baseCriteriaList;
                var currentFilter = options.currentFilter.selectedCriteria;

                $scope.typeSeven = new Array<ExportDetailsFilter>();
                $.each(baseCriteriaList, (index: number, value: IBaseCriteria) => {

                    if ((value.type == 7) && (
                        value.name == "Peer Group name" || // c357e4f0-a840-4df2-fa4e-1099024a7680 Peer Group Name
                        value.name == "Region" || // d0d36a30-844f-40d2-5d04-91b3aff5a776 Region
                        value.name == "Country" || // 9e6c1f08-b407-4660-2b95-5a5b0aa540fe Country
                        value.name == "Sedol"))  // 7c713e99-c525-480f-ba32-cd79fcb855dc Sedol
                    {
                        var exportDetailsFilter = new ExportDetailsFilter();

                        exportDetailsFilter.baseCriteriaList = value;

                        exportDetailsFilter.isDisabled = $scope.CheckInCurrentCriteria(currentFilter, value);

                        $scope.typeSeven.push(exportDetailsFilter);
                    }

                    if ((value.type == 1) && (value.id == "Market Capitalization"))   // 66a14c85-5e13-463e-f898-55318c447ff1 Market Cap.
                    {
                        var exportDetailsFilter = new ExportDetailsFilter();

                        exportDetailsFilter.baseCriteriaList = value;

                        exportDetailsFilter.isDisabled = $scope.CheckInCurrentCriteria(currentFilter, value);

                        $scope.typeSeven.push(exportDetailsFilter);
                    }

                });

            }

            $scope.getExtraFilters = function () {


                $scope.getTypeSixCriterias();
                $scope.getTypeThreeCriterias();
                $scope.getTypeSevenCriterias();
                $scope.getTypeFiveCriterias();
            }

            $scope.CheckInCurrentCriteria = (currentFilter: ISelectedCriteria, baseCriteriaList: IBaseCriteria) => {

                var isDisabled: boolean;

                $.each(currentFilter, (index: number, valueC: ISelectedCriteria) => {
                    if (valueC.name == baseCriteriaList.name) {
                        isDisabled = true;
                    }
                    else
                        isDisabled = false;

                    if (isDisabled)
                        return false;
                });

                return isDisabled;
            }

            $scope.exportCurrentCriteria = (asCSV: boolean) => {
                var taskNumber = 0;

                if (!asCSV) {
                    $rootScope['screeningExportDetails'].CSV = false;
                    taskNumber = 100;
                }
                else {
                    $rootScope['screeningExportDetails'].CSV = true;
                    taskNumber = 101;
                }

                var promise = LongRunningTaskManagerService.runTask('ScreeningTool_' + moment().format("DDMMYYYY"), angular.toJson($rootScope['screeningExportDetails']), taskNumber, true, null);

                $modelInstance.close("done");
            };

            $scope.resetAll = () => {
                $(":input[class=enabled]", "#form").val("").removeAttr("checked").removeAttr("selected");

                $rootScope['screeningExportDetails'].PeerGroup = $rootScope['screeningExportDetails'].PeerGroup = false;
                $rootScope['screeningExportDetails'].Region = $rootScope['screeningExportDetails'].Region = false;
                $rootScope['screeningExportDetails'].Country = $rootScope['screeningExportDetails'].Country = false;
                $rootScope['screeningExportDetails'].MarketCapitalization = $rootScope['screeningExportDetails'].MarketCapitalization = false;
                $rootScope['screeningExportDetails'].Sedol = $rootScope['screeningExportDetails'].Sedol = false;

                $rootScope['screeningExportDetails'].TotalEsgScore = $rootScope['screeningExportDetails'].TotalEsgScore = false;
                $rootScope['screeningExportDetails'].EnvironmentScore = $rootScope['screeningExportDetails'].EnvironmentScore = false;
                $rootScope['screeningExportDetails'].SocialScore = $rootScope['screeningExportDetails'].SocialScore = false;
                $rootScope['screeningExportDetails'].GovernanceScore = $rootScope['screeningExportDetails'].GovernanceScore = false;
                $rootScope['screeningExportDetails'].PreparednessScore = $rootScope['screeningExportDetails'].PreparednessScore = false;
                $rootScope['screeningExportDetails'].DisclosureScore = $rootScope['screeningExportDetails'].DisclosureScore = false;
                $rootScope['screeningExportDetails'].QualitativePerformanceScore = $rootScope['screeningExportDetails'].QualitativePerformanceScore = false;
                $rootScope['screeningExportDetails'].QuantitativePerformanceScore = $rootScope['screeningExportDetails'].QuantitativePerformanceScore = false;

                $rootScope['screeningExportDetails'].StandardIndicatorAnswerCategories = $rootScope['screeningExportDetails'].StandardIndicatorAnswerCategories = true;
                $rootScope['screeningExportDetails'].StandardIndicatorRawScores = $rootScope['screeningExportDetails'].StandardIndicatorRawScores = false;
                $rootScope['screeningExportDetails'].StandardIndicatorWeights = $rootScope['screeningExportDetails'].StandardIndicatorWeights = false;
            };

            $scope.close = () => {
                $modelInstance.close("done");
            }

            $scope.ModifyExtraDetails = (extraDetail: string) => {
                switch (extraDetail) {
                    // Company Info Extras
                    case "Peer Group name":
                        $rootScope['screeningExportDetails'].PeerGroup = $rootScope['screeningExportDetails'].PeerGroup ? false : true;
                        break;
                    case "Region":
                        $rootScope['screeningExportDetails'].Region = $rootScope['screeningExportDetails'].Region ? false : true;
                        break;
                    case "Country":
                        $rootScope['screeningExportDetails'].Country = $rootScope['screeningExportDetails'].Country ? false : true;
                        break;
                    case "Market Capitalization":
                        $rootScope['screeningExportDetails'].MarketCapitalization = $rootScope['screeningExportDetails'].MarketCapitalization ? false : true;
                        break;
                    case "Sedol":
                        $rootScope['screeningExportDetails'].Sedol = $rootScope['screeningExportDetails'].Sedol ? false : true;
                        break;

                    // ESG Performance
                    case "Total ESG Score":
                        $rootScope['screeningExportDetails'].TotalEsgScore = $rootScope['screeningExportDetails'].TotalEsgScore ? false : true;
                        break;
                    case "Environment Score":
                        $rootScope['screeningExportDetails'].EnvironmentScore = $rootScope['screeningExportDetails'].EnvironmentScore ? false : true;
                        break;
                    case "Social Score":
                        $rootScope['screeningExportDetails'].SocialScore = $rootScope['screeningExportDetails'].SocialScore ? false : true;
                        break;
                    case "Governance Score":
                        $rootScope['screeningExportDetails'].GovernanceScore = $rootScope['screeningExportDetails'].GovernanceScore ? false : true;
                        break;
                    case "Preparedness Score":
                        $rootScope['screeningExportDetails'].PreparednessScore = $rootScope['screeningExportDetails'].PreparednessScore ? false : true;
                        break;
                    case "Disclosure Score":
                        $rootScope['screeningExportDetails'].DisclosureScore = $rootScope['screeningExportDetails'].DisclosureScore ? false : true;
                        break;
                    case "Quantitative Performance Score":
                        $rootScope['screeningExportDetails'].QualitativePerformanceScore = $rootScope['screeningExportDetails'].QualitativePerformanceScore ? false : true;
                        break;
                    case "Qualitative Performance Score":
                        $rootScope['screeningExportDetails'].QuantitativePerformanceScore = $rootScope['screeningExportDetails'].QuantitativePerformanceScore ? false : true;
                        break;

                        // Standard Indicators
                    case "AnswerCategory":
                        $rootScope['screeningExportDetails'].StandardIndicatorAnswerCategories = $rootScope['screeningExportDetails'].StandardIndicatorAnswerCategories ? false : true;
                        break;
                    case "RawScore":
                        $rootScope['screeningExportDetails'].StandardIndicatorRawScores = $rootScope['screeningExportDetails'].StandardIndicatorRawScores ? false : true;
                        break;
                    case "WeightedScore":
                        $rootScope['screeningExportDetails'].StandardIndicatorWeights = $rootScope['screeningExportDetails'].StandardIndicatorWeights ? false : true;
                        break;
                    default:
                        break;
                }
            }
        }
    }

    angular.module(screeningToolModuleName)

        .controller('ScreeningToolController', [
        '$scope', '$rootScope', '$q', '$modal', 'notificationFactory', 'staticObjects', 'screeningToolFactory', 'PortfolioService', '$timeout', ($scope, $rootScope, $q, $modal, notificationFactory, staticObjects, screeningToolFactory, PortfolioService, $timeout) =>
            new ScreeningToolController($scope, $rootScope, $q, $modal, notificationFactory, staticObjects, screeningToolFactory, PortfolioService, $timeout)
        ])
        .controller('LoadFilterSelectModalController', [
            '$scope', '$rootScope', 'notificationFactory', 'staticObjects', 'screeningToolFactory', '$modalInstance', 'options', ($scope, $rootScope, notificationFactory, staticObjects, screeningToolFactory, $modalInstance, options) =>
                new LoadFilterSelectModalController($scope, $rootScope, notificationFactory, staticObjects, screeningToolFactory, $modalInstance, options)
        ])
        .controller('SaveFilterModalController', [
            '$scope', '$rootScope', 'notificationFactory', 'staticObjects', 'screeningToolFactory', '$modalInstance', 'options', ($scope, $rootScope, notificationFactory, staticObjects, screeningToolFactory, $modalInstance, options) =>
                new SaveFilterModalController($scope, $rootScope, notificationFactory, staticObjects, screeningToolFactory, $modalInstance, options)
        ])
        .controller('ExportCurrentCriteriaResults', [
            '$scope', '$rootScope', 'staticObjects', 'screeningToolFactory', '$modalInstance', 'options', 'LongRunningTaskManagerService', ($scope, $rootScope, staticObjects, screeningToolFactory, $modelInstance, options, LongRunningTaskManagerService) =>
                new ExportCurrentCriteriaResults($scope, $rootScope, staticObjects, screeningToolFactory, $modelInstance, options, LongRunningTaskManagerService)
        ]);
}
